peertube-router.service.ts 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. import { filter } from 'rxjs/operators'
  2. import { Injectable } from '@angular/core'
  3. import { ActivatedRoute, ActivatedRouteSnapshot, Event, NavigationEnd, Router, Scroll } from '@angular/router'
  4. import { ServerService } from '../server'
  5. export const enum RouterSetting {
  6. NONE = 0,
  7. REUSE_COMPONENT = 1 << 0,
  8. DISABLE_SCROLL_RESTORE = 1 << 1
  9. }
  10. @Injectable()
  11. export class PeerTubeRouterService {
  12. static readonly ROUTE_SETTING_NAME = 's'
  13. constructor (
  14. private route: ActivatedRoute,
  15. private router: Router,
  16. private server: ServerService
  17. ) { }
  18. addRouteSetting (toAdd: RouterSetting) {
  19. if (this.hasRouteSetting(toAdd)) return
  20. const current = this.getRouteSetting()
  21. this.setRouteSetting(current | toAdd)
  22. }
  23. deleteRouteSetting (toDelete: RouterSetting) {
  24. const current = this.getRouteSetting()
  25. this.setRouteSetting(current & ~toDelete)
  26. }
  27. getRouteSetting (snapshot?: ActivatedRouteSnapshot) {
  28. return (snapshot || this.route.snapshot).queryParams[PeerTubeRouterService.ROUTE_SETTING_NAME]
  29. }
  30. setRouteSetting (value: number) {
  31. let path = window.location.pathname
  32. if (!path || path === '/') path = this.server.getHTMLConfig().instance.defaultClientRoute
  33. const queryParams = { [PeerTubeRouterService.ROUTE_SETTING_NAME]: value }
  34. this.router.navigate([ path ], { queryParams, replaceUrl: true, queryParamsHandling: 'merge' })
  35. }
  36. hasRouteSetting (setting: RouterSetting, snapshot?: ActivatedRouteSnapshot) {
  37. return !!(this.getRouteSetting(snapshot) & setting)
  38. }
  39. getNavigationEndEvents () {
  40. return this.router.events.pipe(
  41. filter((e: Event): e is NavigationEnd => e instanceof NavigationEnd)
  42. )
  43. }
  44. getScrollEvents () {
  45. return this.router.events.pipe(
  46. filter((e: Event): e is Scroll => e instanceof Scroll)
  47. )
  48. }
  49. silentNavigate (baseRoute: string[], queryParams: { [id: string]: string }) {
  50. let routeSetting = this.getRouteSetting() ?? RouterSetting.NONE
  51. routeSetting |= RouterSetting.DISABLE_SCROLL_RESTORE
  52. queryParams = {
  53. ...queryParams,
  54. [PeerTubeRouterService.ROUTE_SETTING_NAME]: routeSetting
  55. }
  56. return this.router.navigate(baseRoute, { queryParams })
  57. }
  58. }