2016-06-01 13:29:28 -07:00
|
|
|
import { RouterStateCandidate, ActivatedRouteCandidate, RouterState, ActivatedRoute } from './router_state';
|
|
|
|
import { TreeNode } from './utils/tree';
|
|
|
|
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
|
|
|
|
|
2016-06-01 14:32:15 -07:00
|
|
|
export function createRouterState(curr: RouterStateCandidate, prevState: RouterState): RouterState {
|
|
|
|
const root = createNode(curr._root, prevState ? prevState._root : null);
|
2016-06-01 13:29:28 -07:00
|
|
|
const queryParams = prevState ? prevState.queryParams : new BehaviorSubject(curr.queryParams);
|
|
|
|
const fragment = prevState ? prevState.fragment : new BehaviorSubject(curr.fragment);
|
2016-06-01 14:32:15 -07:00
|
|
|
return new RouterState(root, queryParams, fragment, curr);
|
2016-06-01 13:29:28 -07:00
|
|
|
}
|
|
|
|
|
2016-06-01 14:32:15 -07:00
|
|
|
function createNode(curr:TreeNode<ActivatedRouteCandidate>, prevState?:TreeNode<ActivatedRoute>):TreeNode<ActivatedRoute> {
|
|
|
|
if (prevState && equalRouteCandidates(prevState.value.candidate, curr.value)) {
|
2016-06-01 13:29:28 -07:00
|
|
|
const value = prevState.value;
|
2016-06-01 14:32:15 -07:00
|
|
|
value.candidate = curr.value;
|
|
|
|
|
|
|
|
const children = createOrReuseChildren(curr, prevState);
|
2016-06-01 13:29:28 -07:00
|
|
|
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-01 14:32:15 -07:00
|
|
|
function createOrReuseChildren(curr:TreeNode<ActivatedRouteCandidate>, prevState:TreeNode<ActivatedRoute>) {
|
2016-06-01 13:29:28 -07:00
|
|
|
return curr.children.map(child => {
|
2016-06-01 14:32:15 -07:00
|
|
|
const index = prevState.children.findIndex(p => equalRouteCandidates(p.value.candidate, child.value));
|
2016-06-01 13:29:28 -07:00
|
|
|
if (index >= 0) {
|
2016-06-01 14:32:15 -07:00
|
|
|
return createNode(child, prevState.children[index]);
|
2016-06-01 13:29:28 -07:00
|
|
|
} else {
|
|
|
|
return createNode(child);
|
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
function createActivatedRoute(c:ActivatedRouteCandidate) {
|
2016-06-01 14:32:15 -07:00
|
|
|
return new ActivatedRoute(new BehaviorSubject(c.urlSegments), new BehaviorSubject(c.params), c.outlet, c.component, c);
|
2016-06-01 13:29:28 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
function equalRouteCandidates(a: ActivatedRouteCandidate, b: ActivatedRouteCandidate): boolean {
|
|
|
|
return a._routeConfig === b._routeConfig;
|
|
|
|
}
|