angular-cn/modules/@angular/router/src/create_router_state.ts

56 lines
2.0 KiB
TypeScript
Raw Normal View History

/**
* @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
*/
2016-06-08 14:13:41 -04:00
import {BehaviorSubject} from 'rxjs/BehaviorSubject';
import {ActivatedRoute, ActivatedRouteSnapshot, RouterState, RouterStateSnapshot} from './router_state';
import {TreeNode} from './utils/tree';
export function createRouterState(curr: RouterStateSnapshot, prevState: RouterState): RouterState {
const root = createNode(curr._root, prevState ? prevState._root : undefined);
const queryParams = prevState ? prevState.queryParams : new BehaviorSubject(curr.queryParams);
const fragment = prevState ? prevState.fragment : new BehaviorSubject(curr.fragment);
return new RouterState(root, queryParams, fragment, curr);
}
2016-06-08 14:13:41 -04:00
function createNode(curr: TreeNode<ActivatedRouteSnapshot>, prevState?: TreeNode<ActivatedRoute>):
TreeNode<ActivatedRoute> {
if (prevState && equalRouteSnapshots(prevState.value.snapshot, curr.value)) {
const value = prevState.value;
2016-06-02 17:44:57 -04:00
value._futureSnapshot = curr.value;
2016-06-08 14:13:41 -04:00
const children = createOrReuseChildren(curr, prevState);
return new TreeNode<ActivatedRoute>(value, children);
} else {
const value = createActivatedRoute(curr.value);
const children = curr.children.map(c => createNode(c));
return new TreeNode<ActivatedRoute>(value, children);
}
}
2016-06-08 14:13:41 -04:00
function createOrReuseChildren(
curr: TreeNode<ActivatedRouteSnapshot>, prevState: TreeNode<ActivatedRoute>) {
return curr.children.map(child => {
for (const p of prevState.children) {
if (equalRouteSnapshots(p.value.snapshot, child.value)) {
return createNode(child, p);
}
}
return createNode(child);
});
}
2016-06-08 14:13:41 -04:00
function createActivatedRoute(c: ActivatedRouteSnapshot) {
return new ActivatedRoute(
2016-06-14 17:55:59 -04:00
new BehaviorSubject(c.url), new BehaviorSubject(c.params), c.outlet, c.component, c);
}
function equalRouteSnapshots(a: ActivatedRouteSnapshot, b: ActivatedRouteSnapshot): boolean {
return a._routeConfig === b._routeConfig;
}