1 import * as debug from 'debug'
2 import { pairwise } from 'rxjs'
3 import { ViewportScroller } from '@angular/common'
4 import { Injectable } from '@angular/core'
5 import { RouterSetting } from '../'
6 import { PeerTubeRouterService } from './peertube-router.service'
7 import { logger } from '@root-helpers/logger'
9 const debugLogger = debug('peertube:main:ScrollService')
12 export class ScrollService {
14 private resetScroll = true
17 private viewportScroller: ViewportScroller,
18 private peertubeRouter: PeerTubeRouterService
21 enableScrollRestoration () {
22 // We'll manage scroll restoration ourselves
23 this.viewportScroller.setHistoryScrollRestoration('manual')
29 private produceScroll () {
30 // When we add the a-state parameter, we don't want to alter the scroll
31 this.peertubeRouter.getNavigationEndEvents().pipe(pairwise())
32 .subscribe(([ e1, e2 ]) => {
34 this.resetScroll = false
36 const previousUrl = new URL(window.location.origin + e1.urlAfterRedirects)
37 const nextUrl = new URL(window.location.origin + e2.urlAfterRedirects)
39 if (previousUrl.pathname !== nextUrl.pathname) {
40 this.resetScroll = true
44 if (this.peertubeRouter.hasRouteSetting(RouterSetting.DISABLE_SCROLL_RESTORE)) {
45 this.resetScroll = false
49 // Remove route settings from the comparison
50 const nextSearchParams = nextUrl.searchParams
51 nextSearchParams.delete(PeerTubeRouterService.ROUTE_SETTING_NAME)
53 const previousSearchParams = previousUrl.searchParams
55 nextSearchParams.sort()
56 previousSearchParams.sort()
58 if (nextSearchParams.toString() !== previousSearchParams.toString()) {
59 this.resetScroll = true
62 logger.error('Cannot parse URL to check next scroll.', err)
63 this.resetScroll = true
68 private consumeScroll () {
69 // Handle anchors/restore position
70 this.peertubeRouter.getScrollEvents().subscribe(e => {
71 debugLogger('Will schedule scroll after router event %o.', { e, resetScroll: this.resetScroll })
73 // scrollToAnchor first to preserve anchor position when using history navigation
75 setTimeout(() => this.viewportScroller.scrollToAnchor(e.anchor))
81 setTimeout(() => this.viewportScroller.scrollToPosition(e.position))
86 if (this.resetScroll) {
87 return this.viewportScroller.scrollToPosition([ 0, 0 ])