]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/app/shared/shared-video-playlist/video-add-to-playlist.component.ts
Prevent layout shift in videos list
[github/Chocobozzz/PeerTube.git] / client / src / app / shared / shared-video-playlist / video-add-to-playlist.component.ts
1 import * as debug from 'debug'
2 import { Subject, Subscription } from 'rxjs'
3 import { debounceTime, filter } from 'rxjs/operators'
4 import { ChangeDetectionStrategy, ChangeDetectorRef, Component, Input, OnChanges, OnDestroy, OnInit, SimpleChanges } from '@angular/core'
5 import { AuthService, DisableForReuseHook, Notifier } from '@app/core'
6 import { FormReactive, FormReactiveService } from '@app/shared/shared-forms'
7 import { secondsToTime } from '@shared/core-utils'
8 import {
9 CachedVideoExistInPlaylist,
10 Video,
11 VideoPlaylistCreate,
12 VideoPlaylistElementCreate,
13 VideoPlaylistElementUpdate,
14 VideoPlaylistPrivacy
15 } from '@shared/models'
16 import { VIDEO_PLAYLIST_DISPLAY_NAME_VALIDATOR } from '../form-validators/video-playlist-validators'
17 import { CachedPlaylist, VideoPlaylistService } from './video-playlist.service'
18
19 const debugLogger = debug('peertube:playlists:VideoAddToPlaylistComponent')
20
21 type PlaylistElement = {
22 enabled: boolean
23 playlistElementId?: number
24 startTimestamp?: number
25 stopTimestamp?: number
26 }
27
28 type PlaylistSummary = {
29 id: number
30 displayName: string
31 optionalRowDisplayed: boolean
32
33 elements: PlaylistElement[]
34 }
35
36 @Component({
37 selector: 'my-video-add-to-playlist',
38 styleUrls: [ './video-add-to-playlist.component.scss' ],
39 templateUrl: './video-add-to-playlist.component.html',
40 changeDetection: ChangeDetectionStrategy.OnPush
41 })
42 export class VideoAddToPlaylistComponent extends FormReactive implements OnInit, OnChanges, OnDestroy, DisableForReuseHook {
43 @Input() video: Video
44 @Input() currentVideoTimestamp: number
45 @Input() lazyLoad = false
46
47 isNewPlaylistBlockOpened = false
48
49 videoPlaylistSearch: string
50 videoPlaylistSearchChanged = new Subject<void>()
51
52 videoPlaylists: PlaylistSummary[] = []
53
54 private disabled = false
55
56 private listenToPlaylistChangeSub: Subscription
57 private playlistsData: CachedPlaylist[] = []
58
59 private pendingAddId: number
60
61 constructor (
62 protected formReactiveService: FormReactiveService,
63 private authService: AuthService,
64 private notifier: Notifier,
65 private videoPlaylistService: VideoPlaylistService,
66 private cd: ChangeDetectorRef
67 ) {
68 super()
69 }
70
71 get user () {
72 return this.authService.getUser()
73 }
74
75 ngOnInit () {
76 this.buildForm({
77 displayName: VIDEO_PLAYLIST_DISPLAY_NAME_VALIDATOR
78 })
79
80 this.videoPlaylistService.listenToMyAccountPlaylistsChange()
81 .subscribe(result => {
82 this.playlistsData = result.data
83
84 this.videoPlaylistService.runVideoExistsInPlaylistCheck(this.video.id)
85 })
86
87 this.videoPlaylistSearchChanged
88 .pipe(debounceTime(500))
89 .subscribe(() => this.load())
90
91 if (this.lazyLoad === false) this.load()
92 }
93
94 ngOnChanges (simpleChanges: SimpleChanges) {
95 if (simpleChanges['video']) {
96 this.reload()
97 }
98 }
99
100 ngOnDestroy () {
101 this.unsubscribePlaylistChanges()
102 }
103
104 disableForReuse () {
105 this.disabled = true
106 }
107
108 enabledForReuse () {
109 this.disabled = false
110 }
111
112 reload () {
113 debugLogger('Reloading component')
114
115 this.videoPlaylists = []
116 this.videoPlaylistSearch = undefined
117
118 this.load()
119
120 this.cd.markForCheck()
121 }
122
123 load () {
124 debugLogger('Loading component')
125
126 this.listenToVideoPlaylistChange()
127
128 this.videoPlaylistService.listMyPlaylistWithCache(this.user, this.videoPlaylistSearch)
129 .subscribe(playlistsResult => {
130 this.playlistsData = playlistsResult.data
131
132 this.videoPlaylistService.runVideoExistsInPlaylistCheck(this.video.id)
133 })
134 }
135
136 openChange (opened: boolean) {
137 if (opened === false) {
138 this.isNewPlaylistBlockOpened = false
139 }
140 }
141
142 openCreateBlock (event: Event) {
143 event.preventDefault()
144
145 this.isNewPlaylistBlockOpened = true
146 }
147
148 toggleMainPlaylist (e: Event, playlist: PlaylistSummary) {
149 e.preventDefault()
150
151 if (this.isPresentMultipleTimes(playlist) || playlist.optionalRowDisplayed) return
152
153 if (playlist.elements.length === 0) {
154 const element: PlaylistElement = {
155 enabled: true,
156 playlistElementId: undefined,
157 startTimestamp: 0,
158 stopTimestamp: this.video.duration
159 }
160
161 this.addVideoInPlaylist(playlist, element)
162 } else {
163 this.removeVideoFromPlaylist(playlist, playlist.elements[0].playlistElementId)
164 playlist.elements = []
165 }
166
167 this.cd.markForCheck()
168 }
169
170 toggleOptionalPlaylist (e: Event, playlist: PlaylistSummary, element: PlaylistElement, startTimestamp: number, stopTimestamp: number) {
171 e.preventDefault()
172
173 if (element.enabled) {
174 this.removeVideoFromPlaylist(playlist, element.playlistElementId)
175 element.enabled = false
176
177 // Hide optional rows pane when the user unchecked all the playlists
178 if (this.isPrimaryCheckboxChecked(playlist) === false) {
179 playlist.optionalRowDisplayed = false
180 }
181 } else {
182 const element: PlaylistElement = {
183 enabled: true,
184 playlistElementId: undefined,
185 startTimestamp,
186 stopTimestamp
187 }
188
189 this.addVideoInPlaylist(playlist, element)
190 }
191
192 this.cd.markForCheck()
193 }
194
195 createPlaylist () {
196 const displayName = this.form.value['displayName']
197
198 const videoPlaylistCreate: VideoPlaylistCreate = {
199 displayName,
200 privacy: VideoPlaylistPrivacy.PRIVATE
201 }
202
203 this.videoPlaylistService.createVideoPlaylist(videoPlaylistCreate)
204 .subscribe({
205 next: () => {
206 this.isNewPlaylistBlockOpened = false
207
208 this.cd.markForCheck()
209 },
210
211 error: err => this.notifier.error(err.message)
212 })
213 }
214
215 onVideoPlaylistSearchChanged () {
216 this.videoPlaylistSearchChanged.next()
217 }
218
219 isPrimaryCheckboxChecked (playlist: PlaylistSummary) {
220 // Reduce latency when adding a video to a playlist using pendingAddId
221 return this.pendingAddId === playlist.id ||
222 playlist.elements.filter(e => e.enabled).length !== 0
223 }
224
225 toggleOptionalRow (playlist: PlaylistSummary) {
226 playlist.optionalRowDisplayed = !playlist.optionalRowDisplayed
227
228 this.cd.markForCheck()
229 }
230
231 getPrimaryInputName (playlist: PlaylistSummary) {
232 return 'in-playlist-primary-' + playlist.id
233 }
234
235 getOptionalInputName (playlist: PlaylistSummary, element?: PlaylistElement) {
236 const suffix = element
237 ? '-' + element.playlistElementId
238 : ''
239
240 return 'in-playlist-optional-' + playlist.id + suffix
241 }
242
243 buildOptionalRowElements (playlist: PlaylistSummary) {
244 const elements = playlist.elements
245
246 const lastElement = elements.length === 0
247 ? undefined
248 : elements[elements.length - 1]
249
250 // Build an empty last element
251 if (!lastElement || lastElement.enabled === true) {
252 elements.push({
253 enabled: false,
254 startTimestamp: 0,
255 stopTimestamp: this.video.duration
256 })
257 }
258
259 return elements
260 }
261
262 isPresentMultipleTimes (playlist: PlaylistSummary) {
263 return playlist.elements.filter(e => e.enabled === true).length > 1
264 }
265
266 onElementTimestampUpdate (playlist: PlaylistSummary, element: PlaylistElement) {
267 if (!element.playlistElementId || element.enabled === false) return
268
269 const body: VideoPlaylistElementUpdate = {
270 startTimestamp: element.startTimestamp,
271 stopTimestamp: element.stopTimestamp
272 }
273
274 this.videoPlaylistService.updateVideoOfPlaylist(playlist.id, element.playlistElementId, body, this.video.id)
275 .subscribe({
276 next: () => {
277 this.notifier.success($localize`Timestamps updated`)
278 },
279
280 error: err => this.notifier.error(err.message),
281
282 complete: () => this.cd.markForCheck()
283 })
284 }
285
286 private isOptionalRowDisplayed (playlist: PlaylistSummary) {
287 const elements = playlist.elements.filter(e => e.enabled)
288
289 if (elements.length > 1) return true
290
291 if (elements.length === 1) {
292 const element = elements[0]
293
294 if (
295 (element.startTimestamp && element.startTimestamp !== 0) ||
296 (element.stopTimestamp && element.stopTimestamp !== this.video.duration)
297 ) {
298 return true
299 }
300 }
301
302 return false
303 }
304
305 private removeVideoFromPlaylist (playlist: PlaylistSummary, elementId: number) {
306 this.videoPlaylistService.removeVideoFromPlaylist(playlist.id, elementId, this.video.id)
307 .subscribe({
308 next: () => {
309 this.notifier.success($localize`Video removed from ${playlist.displayName}`)
310 },
311
312 error: err => this.notifier.error(err.message),
313
314 complete: () => this.cd.markForCheck()
315 })
316 }
317
318 private listenToVideoPlaylistChange () {
319 this.unsubscribePlaylistChanges()
320
321 this.listenToPlaylistChangeSub = this.videoPlaylistService.listenToVideoPlaylistChange(this.video.id)
322 .pipe(filter(() => this.disabled === false))
323 .subscribe(existResult => this.rebuildPlaylists(existResult))
324 }
325
326 private unsubscribePlaylistChanges () {
327 if (this.listenToPlaylistChangeSub) {
328 this.listenToPlaylistChangeSub.unsubscribe()
329 this.listenToPlaylistChangeSub = undefined
330 }
331 }
332
333 private rebuildPlaylists (existResult: CachedVideoExistInPlaylist[]) {
334 debugLogger('Got existing results for %d.', this.video.id, existResult)
335
336 const oldPlaylists = this.videoPlaylists
337
338 this.videoPlaylists = []
339 for (const playlist of this.playlistsData) {
340 const existingPlaylists = existResult.filter(p => p.playlistId === playlist.id)
341
342 const playlistSummary = {
343 id: playlist.id,
344 optionalRowDisplayed: false,
345 displayName: playlist.displayName,
346 elements: existingPlaylists.map(e => ({
347 enabled: true,
348 playlistElementId: e.playlistElementId,
349 startTimestamp: e.startTimestamp || 0,
350 stopTimestamp: e.stopTimestamp || this.video.duration
351 }))
352 }
353
354 const oldPlaylist = oldPlaylists.find(p => p.id === playlist.id)
355 playlistSummary.optionalRowDisplayed = oldPlaylist
356 ? oldPlaylist.optionalRowDisplayed
357 : this.isOptionalRowDisplayed(playlistSummary)
358
359 this.videoPlaylists.push(playlistSummary)
360 }
361
362 debugLogger('Rebuilt playlist state for video %d.', this.video.id, this.videoPlaylists)
363
364 this.cd.markForCheck()
365 }
366
367 private addVideoInPlaylist (playlist: PlaylistSummary, element: PlaylistElement) {
368 const body: VideoPlaylistElementCreate = { videoId: this.video.id }
369
370 if (element.startTimestamp) body.startTimestamp = element.startTimestamp
371 if (element.stopTimestamp && element.stopTimestamp !== this.video.duration) body.stopTimestamp = element.stopTimestamp
372
373 this.pendingAddId = playlist.id
374
375 this.videoPlaylistService.addVideoInPlaylist(playlist.id, body)
376 .subscribe({
377 next: res => {
378 const message = body.startTimestamp || body.stopTimestamp
379 ? $localize`Video added in ${playlist.displayName} at timestamps ${this.formatTimestamp(element)}`
380 : $localize`Video added in ${playlist.displayName}`
381
382 this.notifier.success(message)
383
384 if (element) element.playlistElementId = res.videoPlaylistElement.id
385 },
386
387 error: err => {
388 this.pendingAddId = undefined
389 this.cd.markForCheck()
390
391 this.notifier.error(err.message)
392 },
393
394 complete: () => {
395 this.pendingAddId = undefined
396 this.cd.markForCheck()
397 }
398 })
399 }
400
401 private formatTimestamp (element: PlaylistElement) {
402 const start = element.startTimestamp ? secondsToTime(element.startTimestamp) : ''
403 const stop = element.stopTimestamp ? secondsToTime(element.stopTimestamp) : ''
404
405 return `(${start}-${stop})`
406 }
407 }