1 import { ComponentRef, Injectable } from '@angular/core'
2 import { ActivatedRouteSnapshot, DetachedRouteHandle, RouteReuseStrategy } from '@angular/router'
3 import { DisableForReuseHook } from './disable-for-reuse-hook'
4 import { PeerTubeRouterService, RouterSetting } from './peertube-router.service'
7 export class CustomReuseStrategy implements RouteReuseStrategy {
8 storedRouteHandles = new Map<string, DetachedRouteHandle>()
11 private readonly MAX_SIZE = 2
13 // Decides if the route should be stored
14 shouldDetach (route: ActivatedRouteSnapshot): boolean {
15 return this.isReuseEnabled(route)
18 // Store the information for the route we're destructing
19 store (route: ActivatedRouteSnapshot, handle: DetachedRouteHandle): void {
22 const key = this.generateKey(route)
23 this.recentlyUsed = key
25 console.log('Storing component %s to reuse later.', key)
27 const componentRef = (handle as any).componentRef as ComponentRef<DisableForReuseHook>
28 componentRef.instance.disableForReuse()
29 componentRef.changeDetectorRef.detectChanges()
31 this.storedRouteHandles.set(key, handle)
36 // Return true if we have a stored route object for the next route
37 shouldAttach (route: ActivatedRouteSnapshot): boolean {
38 const key = this.generateKey(route)
39 return this.isReuseEnabled(route) && this.storedRouteHandles.has(key)
42 // If we returned true in shouldAttach(), now return the actual route data for restoration
43 retrieve (route: ActivatedRouteSnapshot): DetachedRouteHandle {
44 if (!this.isReuseEnabled(route)) return undefined
46 const key = this.generateKey(route)
47 this.recentlyUsed = key
49 console.log('Reusing component %s.', key)
51 const handle = this.storedRouteHandles.get(key)
52 if (!handle) return handle;
54 (handle as any).componentRef.instance.enabledForReuse()
59 // Reuse the route if we're going to and from the same route
60 shouldReuseRoute (future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {
61 return future.routeConfig === curr.routeConfig
65 if (this.storedRouteHandles.size >= this.MAX_SIZE) {
66 this.storedRouteHandles.forEach((r, key) => {
67 if (key === this.recentlyUsed) return
69 console.log('Removing stored component %s.', key);
71 (r as any).componentRef.destroy()
72 this.storedRouteHandles.delete(key)
77 private generateKey (route: ActivatedRouteSnapshot) {
78 const reuse = route.data.reuse
79 if (!reuse) return undefined
81 return reuse.key + JSON.stringify(route.queryParams)
84 private isReuseEnabled (route: ActivatedRouteSnapshot) {
85 // Cannot use peertube router here because of cyclic router dependency
86 return route.data.reuse?.enabled &&
87 !!(route.queryParams[PeerTubeRouterService.ROUTE_SETTING_NAME] & RouterSetting.REUSE_COMPONENT)