89 lines
2.8 KiB
TypeScript
89 lines
2.8 KiB
TypeScript
import { ActivatedRouteSnapshot, DetachedRouteHandle, RouteReuseStrategy } from '@angular/router';
|
|
import { Debounce } from '../utils';
|
|
|
|
export interface OnAttach {
|
|
ngOnAttach(previousRoute?: ActivatedRouteSnapshot): void;
|
|
}
|
|
|
|
export interface OnDetach {
|
|
ngOnDetach(): void;
|
|
}
|
|
|
|
interface RouteStorageObject {
|
|
handle: DetachedRouteHandle;
|
|
previousRoute: ActivatedRouteSnapshot;
|
|
}
|
|
|
|
export class CustomRouteReuseStrategy implements RouteReuseStrategy {
|
|
private _storedRoutes: { [key: string]: RouteStorageObject } = {};
|
|
|
|
private static _removeTooltips(): void {
|
|
while (document.getElementsByTagName('mat-tooltip-component').length > 0) {
|
|
document.getElementsByTagName('mat-tooltip-component')[0].remove();
|
|
}
|
|
}
|
|
|
|
shouldDetach(route: ActivatedRouteSnapshot): boolean {
|
|
if (!route?.routeConfig?.data) {
|
|
return false;
|
|
}
|
|
return !!route.routeConfig.data.reuse && !!this._getKey(route);
|
|
}
|
|
|
|
store(route: ActivatedRouteSnapshot, handle: DetachedRouteHandle): void {
|
|
if (handle === null) {
|
|
return;
|
|
}
|
|
CustomRouteReuseStrategy._removeTooltips();
|
|
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
const element: any = handle;
|
|
|
|
if (element?.componentRef?.instance?.ngOnDetach) {
|
|
this._onDetach(element.componentRef?.instance);
|
|
}
|
|
|
|
this._storedRoutes[this._getKey(route)] = {
|
|
handle: element as DetachedRouteHandle,
|
|
previousRoute: route,
|
|
};
|
|
}
|
|
|
|
shouldAttach(route: ActivatedRouteSnapshot): boolean {
|
|
return !!this._storedRoutes[this._getKey(route)];
|
|
}
|
|
|
|
retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle {
|
|
const key = this._getKey(route);
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
const element: any = this._storedRoutes[key]?.handle;
|
|
|
|
if (element?.componentRef?.instance?.ngOnAttach) {
|
|
this._onAttach(element.componentRef?.instance, this._storedRoutes[key].previousRoute);
|
|
}
|
|
|
|
return element as DetachedRouteHandle;
|
|
}
|
|
|
|
shouldReuseRoute(future: ActivatedRouteSnapshot, current: ActivatedRouteSnapshot): boolean {
|
|
return future.routeConfig === current.routeConfig || this._getKey(future) === this._getKey(current);
|
|
}
|
|
|
|
private _getKey(route: ActivatedRouteSnapshot): string {
|
|
return route.pathFromRoot
|
|
.map((el: ActivatedRouteSnapshot) => (el.routeConfig ? `${el.routeConfig.path}${JSON.stringify(el.params)}` : ''))
|
|
.filter(str => str.length > 0)
|
|
.join('');
|
|
}
|
|
|
|
@Debounce()
|
|
private _onAttach(instance: OnAttach, previousRoute?: ActivatedRouteSnapshot) {
|
|
instance.ngOnAttach(previousRoute);
|
|
}
|
|
|
|
@Debounce()
|
|
private _onDetach(instance: OnDetach) {
|
|
instance.ngOnDetach();
|
|
}
|
|
}
|