/
pre_activation.ts
364 lines (318 loc) Β· 14.1 KB
/
pre_activation.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {Injector} from '@angular/core';
import {Observable} from 'rxjs/Observable';
import {from} from 'rxjs/observable/from';
import {of } from 'rxjs/observable/of';
import {concatMap} from 'rxjs/operator/concatMap';
import {every} from 'rxjs/operator/every';
import {first} from 'rxjs/operator/first';
import {last} from 'rxjs/operator/last';
import {map} from 'rxjs/operator/map';
import {mergeMap} from 'rxjs/operator/mergeMap';
import {reduce} from 'rxjs/operator/reduce';
import {LoadedRouterConfig, ResolveData, RunGuardsAndResolvers} from './config';
import {ActivationStart, ChildActivationStart, Event} from './events';
import {ChildrenOutletContexts, OutletContext} from './router_outlet_context';
import {ActivatedRouteSnapshot, ParamsInheritanceStrategy, RouterStateSnapshot, equalParamsAndUrlSegments, inheritedParamsDataResolve} from './router_state';
import {andObservables, forEach, shallowEqual, wrapIntoObservable} from './utils/collection';
import {TreeNode, nodeChildrenAsMap} from './utils/tree';
class CanActivate {
readonly route: ActivatedRouteSnapshot;
constructor(public path: ActivatedRouteSnapshot[]) {
this.route = this.path[this.path.length - 1];
}
}
class CanDeactivate {
constructor(public component: Object|null, public route: ActivatedRouteSnapshot) {}
}
/**
* This class bundles the actions involved in preactivation of a route.
*/
export class PreActivation {
private canActivateChecks: CanActivate[] = [];
private canDeactivateChecks: CanDeactivate[] = [];
constructor(
private future: RouterStateSnapshot, private curr: RouterStateSnapshot,
private moduleInjector: Injector, private forwardEvent?: (evt: Event) => void) {}
initialize(parentContexts: ChildrenOutletContexts): void {
const futureRoot = this.future._root;
const currRoot = this.curr ? this.curr._root : null;
this.setupChildRouteGuards(futureRoot, currRoot, parentContexts, [futureRoot.value]);
}
checkGuards(): Observable<boolean> {
if (!this.isDeactivating() && !this.isActivating()) {
return of (true);
}
const canDeactivate$ = this.runCanDeactivateChecks();
return mergeMap.call(
canDeactivate$,
(canDeactivate: boolean) => canDeactivate ? this.runCanActivateChecks() : of (false));
}
resolveData(paramsInheritanceStrategy: ParamsInheritanceStrategy): Observable<any> {
if (!this.isActivating()) return of (null);
const checks$ = from(this.canActivateChecks);
const runningChecks$ = concatMap.call(
checks$, (check: CanActivate) => this.runResolve(check.route, paramsInheritanceStrategy));
return reduce.call(runningChecks$, (_: any, __: any) => _);
}
isDeactivating(): boolean { return this.canDeactivateChecks.length !== 0; }
isActivating(): boolean { return this.canActivateChecks.length !== 0; }
/**
* Iterates over child routes and calls recursive `setupRouteGuards` to get `this` instance in
* proper state to run `checkGuards()` method.
*/
private setupChildRouteGuards(
futureNode: TreeNode<ActivatedRouteSnapshot>, currNode: TreeNode<ActivatedRouteSnapshot>|null,
contexts: ChildrenOutletContexts|null, futurePath: ActivatedRouteSnapshot[]): void {
const prevChildren = nodeChildrenAsMap(currNode);
// Process the children of the future route
futureNode.children.forEach(c => {
this.setupRouteGuards(
c, prevChildren[c.value.outlet], contexts, futurePath.concat([c.value]));
delete prevChildren[c.value.outlet];
});
// Process any children left from the current route (not active for the future route)
forEach(
prevChildren, (v: TreeNode<ActivatedRouteSnapshot>, k: string) =>
this.deactivateRouteAndItsChildren(v, contexts !.getContext(k)));
}
/**
* Iterates over child routes and calls recursive `setupRouteGuards` to get `this` instance in
* proper state to run `checkGuards()` method.
*/
private setupRouteGuards(
futureNode: TreeNode<ActivatedRouteSnapshot>, currNode: TreeNode<ActivatedRouteSnapshot>,
parentContexts: ChildrenOutletContexts|null, futurePath: ActivatedRouteSnapshot[]): void {
const future = futureNode.value;
const curr = currNode ? currNode.value : null;
const context = parentContexts ? parentContexts.getContext(futureNode.value.outlet) : null;
// reusing the node
if (curr && future.routeConfig === curr.routeConfig) {
const shouldRunGuardsAndResolvers = this.shouldRunGuardsAndResolvers(
curr, future, future.routeConfig !.runGuardsAndResolvers);
if (shouldRunGuardsAndResolvers) {
this.canActivateChecks.push(new CanActivate(futurePath));
} else {
// we need to set the data
future.data = curr.data;
future._resolvedData = curr._resolvedData;
}
// If we have a component, we need to go through an outlet.
if (future.component) {
this.setupChildRouteGuards(
futureNode, currNode, context ? context.children : null, futurePath);
// if we have a componentless route, we recurse but keep the same outlet map.
} else {
this.setupChildRouteGuards(futureNode, currNode, parentContexts, futurePath);
}
if (shouldRunGuardsAndResolvers) {
const outlet = context !.outlet !;
this.canDeactivateChecks.push(new CanDeactivate(outlet.component, curr));
}
} else {
if (curr) {
this.deactivateRouteAndItsChildren(currNode, context);
}
this.canActivateChecks.push(new CanActivate(futurePath));
// If we have a component, we need to go through an outlet.
if (future.component) {
this.setupChildRouteGuards(futureNode, null, context ? context.children : null, futurePath);
// if we have a componentless route, we recurse but keep the same outlet map.
} else {
this.setupChildRouteGuards(futureNode, null, parentContexts, futurePath);
}
}
}
private shouldRunGuardsAndResolvers(
curr: ActivatedRouteSnapshot, future: ActivatedRouteSnapshot,
mode: RunGuardsAndResolvers|undefined): boolean {
switch (mode) {
case 'always':
return true;
case 'paramsOrQueryParamsChange':
return !equalParamsAndUrlSegments(curr, future) ||
!shallowEqual(curr.queryParams, future.queryParams);
case 'paramsChange':
default:
return !equalParamsAndUrlSegments(curr, future);
}
}
private deactivateRouteAndItsChildren(
route: TreeNode<ActivatedRouteSnapshot>, context: OutletContext|null): void {
const children = nodeChildrenAsMap(route);
const r = route.value;
forEach(children, (node: TreeNode<ActivatedRouteSnapshot>, childName: string) => {
if (!r.component) {
this.deactivateRouteAndItsChildren(node, context);
} else if (context) {
this.deactivateRouteAndItsChildren(node, context.children.getContext(childName));
} else {
this.deactivateRouteAndItsChildren(node, null);
}
});
if (!r.component) {
this.canDeactivateChecks.push(new CanDeactivate(null, r));
} else if (context && context.outlet && context.outlet.isActivated) {
this.canDeactivateChecks.push(new CanDeactivate(context.outlet.component, r));
} else {
this.canDeactivateChecks.push(new CanDeactivate(null, r));
}
}
private runCanDeactivateChecks(): Observable<boolean> {
const checks$ = from(this.canDeactivateChecks);
const runningChecks$ = mergeMap.call(
checks$, (check: CanDeactivate) => this.runCanDeactivate(check.component, check.route));
return every.call(runningChecks$, (result: boolean) => result === true);
}
private runCanActivateChecks(): Observable<boolean> {
const checks$ = from(this.canActivateChecks);
const runningChecks$ = concatMap.call(
checks$,
(check: CanActivate) => andObservables(from([
this.fireChildActivationStart(check.route.parent), this.fireActivationStart(check.route),
this.runCanActivateChild(check.path), this.runCanActivate(check.route)
])));
return every.call(runningChecks$, (result: boolean) => result === true);
// this.fireChildActivationStart(check.path),
}
/**
* This should fire off `ActivationStart` events for each route being activated at this
* level.
* In other words, if you're activating `a` and `b` below, `path` will contain the
* `ActivatedRouteSnapshot`s for both and we will fire `ActivationStart` for both. Always
* return
* `true` so checks continue to run.
*/
private fireActivationStart(snapshot: ActivatedRouteSnapshot|null): Observable<boolean> {
if (snapshot !== null && this.forwardEvent) {
this.forwardEvent(new ActivationStart(snapshot));
}
return of (true);
}
/**
* This should fire off `ChildActivationStart` events for each route being activated at this
* level.
* In other words, if you're activating `a` and `b` below, `path` will contain the
* `ActivatedRouteSnapshot`s for both and we will fire `ChildActivationStart` for both. Always
* return
* `true` so checks continue to run.
*/
private fireChildActivationStart(snapshot: ActivatedRouteSnapshot|null): Observable<boolean> {
if (snapshot !== null && this.forwardEvent) {
this.forwardEvent(new ChildActivationStart(snapshot));
}
return of (true);
}
private runCanActivate(future: ActivatedRouteSnapshot): Observable<boolean> {
const canActivate = future.routeConfig ? future.routeConfig.canActivate : null;
if (!canActivate || canActivate.length === 0) return of (true);
const obs = map.call(from(canActivate), (c: any) => {
const guard = this.getToken(c, future);
let observable: Observable<boolean>;
if (guard.canActivate) {
observable = wrapIntoObservable(guard.canActivate(future, this.future));
} else {
observable = wrapIntoObservable(guard(future, this.future));
}
return first.call(observable);
});
return andObservables(obs);
}
private runCanActivateChild(path: ActivatedRouteSnapshot[]): Observable<boolean> {
const future = path[path.length - 1];
const canActivateChildGuards = path.slice(0, path.length - 1)
.reverse()
.map(p => this.extractCanActivateChild(p))
.filter(_ => _ !== null);
return andObservables(map.call(from(canActivateChildGuards), (d: any) => {
const obs = map.call(from(d.guards), (c: any) => {
const guard = this.getToken(c, d.node);
let observable: Observable<boolean>;
if (guard.canActivateChild) {
observable = wrapIntoObservable(guard.canActivateChild(future, this.future));
} else {
observable = wrapIntoObservable(guard(future, this.future));
}
return first.call(observable);
});
return andObservables(obs);
}));
}
private extractCanActivateChild(p: ActivatedRouteSnapshot):
{node: ActivatedRouteSnapshot, guards: any[]}|null {
const canActivateChild = p.routeConfig ? p.routeConfig.canActivateChild : null;
if (!canActivateChild || canActivateChild.length === 0) return null;
return {node: p, guards: canActivateChild};
}
private runCanDeactivate(component: Object|null, curr: ActivatedRouteSnapshot):
Observable<boolean> {
const canDeactivate = curr && curr.routeConfig ? curr.routeConfig.canDeactivate : null;
if (!canDeactivate || canDeactivate.length === 0) return of (true);
const canDeactivate$ = mergeMap.call(from(canDeactivate), (c: any) => {
const guard = this.getToken(c, curr);
let observable: Observable<boolean>;
if (guard.canDeactivate) {
observable =
wrapIntoObservable(guard.canDeactivate(component, curr, this.curr, this.future));
} else {
observable = wrapIntoObservable(guard(component, curr, this.curr, this.future));
}
return first.call(observable);
});
return every.call(canDeactivate$, (result: any) => result === true);
}
private runResolve(
future: ActivatedRouteSnapshot,
paramsInheritanceStrategy: ParamsInheritanceStrategy): Observable<any> {
const resolve = future._resolve;
return map.call(this.resolveNode(resolve, future), (resolvedData: any): any => {
future._resolvedData = resolvedData;
future.data = {...future.data,
...inheritedParamsDataResolve(future, paramsInheritanceStrategy).resolve};
return null;
});
}
private resolveNode(resolve: ResolveData, future: ActivatedRouteSnapshot): Observable<any> {
const keys = Object.keys(resolve);
if (keys.length === 0) {
return of ({});
}
if (keys.length === 1) {
const key = keys[0];
return map.call(
this.getResolver(resolve[key], future), (value: any) => { return {[key]: value}; });
}
const data: {[k: string]: any} = {};
const runningResolvers$ = mergeMap.call(from(keys), (key: string) => {
return map.call(this.getResolver(resolve[key], future), (value: any) => {
data[key] = value;
return value;
});
});
return map.call(last.call(runningResolvers$), () => data);
}
private getResolver(injectionToken: any, future: ActivatedRouteSnapshot): Observable<any> {
const resolver = this.getToken(injectionToken, future);
return resolver.resolve ? wrapIntoObservable(resolver.resolve(future, this.future)) :
wrapIntoObservable(resolver(future, this.future));
}
private getToken(token: any, snapshot: ActivatedRouteSnapshot): any {
const config = closestLoadedConfig(snapshot);
const injector = config ? config.module.injector : this.moduleInjector;
return injector.get(token);
}
}
function closestLoadedConfig(snapshot: ActivatedRouteSnapshot): LoadedRouterConfig|null {
if (!snapshot) return null;
for (let s = snapshot.parent; s; s = s.parent) {
const route = s.routeConfig;
if (route && route._loadedConfig) return route._loadedConfig;
}
return null;
}