feat(router): implement terminal

This commit is contained in:
vsavkin
2016-06-14 14:55:59 -07:00
parent 503b07f698
commit 127401598b
17 changed files with 1069 additions and 744 deletions

View File

@ -2,171 +2,159 @@ import {Type} from '@angular/core';
import {Observable} from 'rxjs/Observable';
import {of } from 'rxjs/observable/of';
import {match} from './apply_redirects';
import {Route, RouterConfig} from './config';
import {ActivatedRouteSnapshot, RouterStateSnapshot} from './router_state';
import {PRIMARY_OUTLET} from './shared';
import {UrlSegment, UrlTree} from './url_tree';
import {first, flatten, forEach, merge} from './utils/collection';
import {UrlPathWithParams, UrlSegment, UrlTree, mapChildrenIntoArray} from './url_tree';
import {last, merge} from './utils/collection';
import {TreeNode} from './utils/tree';
class CannotRecognize {}
class NoMatch {
constructor(public segment: UrlSegment = null) {}
}
export function recognize(
rootComponentType: Type, config: RouterConfig, url: UrlTree): Observable<RouterStateSnapshot> {
rootComponentType: Type, config: RouterConfig, urlTree: UrlTree,
url: string): Observable<RouterStateSnapshot> {
try {
const match = new MatchResult(
rootComponentType, config, [url.root], {}, url._root.children, [], PRIMARY_OUTLET, null,
url.root);
const roots = constructActivatedRoute(match);
return of (new RouterStateSnapshot(roots[0], url.queryParams, url.fragment));
const children = processSegment(config, urlTree.root, PRIMARY_OUTLET);
const root = new ActivatedRouteSnapshot(
[], {}, PRIMARY_OUTLET, rootComponentType, null, urlTree.root, -1);
const rootNode = new TreeNode<ActivatedRouteSnapshot>(root, children);
return of (new RouterStateSnapshot(url, rootNode, urlTree.queryParams, urlTree.fragment));
} catch (e) {
if (e instanceof CannotRecognize) {
if (e instanceof NoMatch) {
return new Observable<RouterStateSnapshot>(
obs => obs.error(new Error('Cannot match any routes')));
obs => obs.error(new Error(`Cannot match any routes: '${e.segment}'`)));
} else {
return new Observable<RouterStateSnapshot>(obs => obs.error(e));
}
}
}
function constructActivatedRoute(match: MatchResult): TreeNode<ActivatedRouteSnapshot>[] {
const activatedRoute = createActivatedRouteSnapshot(match);
const children = match.leftOverUrl.length > 0 ?
recognizeMany(match.children, match.leftOverUrl) :
recognizeLeftOvers(match.children, match.lastUrlSegment);
function processSegment(
config: Route[], segment: UrlSegment, outlet: string): TreeNode<ActivatedRouteSnapshot>[] {
if (segment.pathsWithParams.length === 0 && Object.keys(segment.children).length > 0) {
return processSegmentChildren(config, segment);
} else {
return [processPathsWithParams(config, segment, 0, segment.pathsWithParams, outlet)];
}
}
function processSegmentChildren(
config: Route[], segment: UrlSegment): TreeNode<ActivatedRouteSnapshot>[] {
const children = mapChildrenIntoArray(
segment, (child, childOutlet) => processSegment(config, child, childOutlet));
checkOutletNameUniqueness(children);
children.sort((a, b) => {
sortActivatedRouteSnapshots(children);
return children;
}
function sortActivatedRouteSnapshots(nodes: TreeNode<ActivatedRouteSnapshot>[]): void {
nodes.sort((a, b) => {
if (a.value.outlet === PRIMARY_OUTLET) return -1;
if (b.value.outlet === PRIMARY_OUTLET) return 1;
return a.value.outlet.localeCompare(b.value.outlet);
});
return [new TreeNode<ActivatedRouteSnapshot>(activatedRoute, children)];
}
function recognizeLeftOvers(
config: Route[], lastUrlSegment: UrlSegment): TreeNode<ActivatedRouteSnapshot>[] {
if (!config) return [];
const mIndex = matchIndex(config, [], lastUrlSegment);
return mIndex ? constructActivatedRoute(mIndex) : [];
}
function recognizeMany(
config: Route[], urls: TreeNode<UrlSegment>[]): TreeNode<ActivatedRouteSnapshot>[] {
return flatten(urls.map(url => recognizeOne(config, url)));
}
function createActivatedRouteSnapshot(match: MatchResult): ActivatedRouteSnapshot {
return new ActivatedRouteSnapshot(
match.consumedUrlSegments, match.parameters, match.outlet, match.component, match.route,
match.lastUrlSegment);
}
function recognizeOne(
config: Route[], url: TreeNode<UrlSegment>): TreeNode<ActivatedRouteSnapshot>[] {
const matches = matchNode(config, url);
for (let match of matches) {
function processPathsWithParams(
config: Route[], segment: UrlSegment, pathIndex: number, paths: UrlPathWithParams[],
outlet: string): TreeNode<ActivatedRouteSnapshot> {
for (let r of config) {
try {
const primary = constructActivatedRoute(match);
const secondary = recognizeMany(config, match.secondary);
const res = primary.concat(secondary);
checkOutletNameUniqueness(res);
return res;
return processPathsWithParamsAgainstRoute(r, segment, pathIndex, paths, outlet);
} catch (e) {
if (!(e instanceof CannotRecognize)) {
throw e;
}
if (!(e instanceof NoMatch)) throw e;
}
}
throw new CannotRecognize();
throw new NoMatch(segment);
}
function checkOutletNameUniqueness(nodes: TreeNode<ActivatedRouteSnapshot>[]):
TreeNode<ActivatedRouteSnapshot>[] {
let names = {};
function processPathsWithParamsAgainstRoute(
route: Route, segment: UrlSegment, pathIndex: number, paths: UrlPathWithParams[],
outlet: string): TreeNode<ActivatedRouteSnapshot> {
if (route.redirectTo) throw new NoMatch();
if ((route.outlet ? route.outlet : PRIMARY_OUTLET) !== outlet) throw new NoMatch();
if (route.path === '**') {
const params = paths.length > 0 ? last(paths).parameters : {};
const snapshot =
new ActivatedRouteSnapshot(paths, params, outlet, route.component, route, segment, -1);
return new TreeNode<ActivatedRouteSnapshot>(snapshot, []);
}
const {consumedPaths, parameters, lastChild} = match(segment, route, paths);
const snapshot = new ActivatedRouteSnapshot(
consumedPaths, parameters, outlet, route.component, route, segment,
pathIndex + lastChild - 1);
const slicedPath = paths.slice(lastChild);
const childConfig = route.children ? route.children : [];
if (childConfig.length === 0 && slicedPath.length === 0) {
return new TreeNode<ActivatedRouteSnapshot>(snapshot, []);
// TODO: check that the right segment is present
} else if (slicedPath.length === 0 && Object.keys(segment.children).length > 0) {
const children = processSegmentChildren(childConfig, segment);
return new TreeNode<ActivatedRouteSnapshot>(snapshot, children);
} else {
const child = processPathsWithParams(
childConfig, segment, pathIndex + lastChild, slicedPath, PRIMARY_OUTLET);
return new TreeNode<ActivatedRouteSnapshot>(snapshot, [child]);
}
}
function match(segment: UrlSegment, route: Route, paths: UrlPathWithParams[]) {
if (route.index || route.path === '' || route.path === '/') {
if (route.terminal && (Object.keys(segment.children).length > 0 || paths.length > 0)) {
throw new NoMatch();
} else {
return {consumedPaths: [], lastChild: 0, parameters: {}};
}
}
const path = route.path.startsWith('/') ? route.path.substring(1) : route.path;
const parts = path.split('/');
const posParameters = {};
const consumedPaths = [];
let currentIndex = 0;
for (let i = 0; i < parts.length; ++i) {
if (currentIndex >= paths.length) throw new NoMatch();
const current = paths[currentIndex];
const p = parts[i];
const isPosParam = p.startsWith(':');
if (!isPosParam && p !== current.path) throw new NoMatch();
if (isPosParam) {
posParameters[p.substring(1)] = current.path;
}
consumedPaths.push(current);
currentIndex++;
}
if (route.terminal && (Object.keys(segment.children).length > 0 || currentIndex < paths.length)) {
throw new NoMatch();
}
const parameters = <any>merge(posParameters, consumedPaths[consumedPaths.length - 1].parameters);
return {consumedPaths, lastChild: currentIndex, parameters};
}
function checkOutletNameUniqueness(nodes: TreeNode<ActivatedRouteSnapshot>[]): void {
const names = {};
nodes.forEach(n => {
let routeWithSameOutletName = names[n.value.outlet];
if (routeWithSameOutletName) {
const p = routeWithSameOutletName.urlSegments.map(s => s.toString()).join('/');
const c = n.value.urlSegments.map(s => s.toString()).join('/');
const c = n.value.url.map(s => s.toString()).join('/');
throw new Error(`Two segments cannot have the same outlet name: '${p}' and '${c}'.`);
}
names[n.value.outlet] = n.value;
});
return nodes;
}
function matchNode(config: Route[], url: TreeNode<UrlSegment>): MatchResult[] {
const res = [];
for (let r of config) {
const m = matchWithParts(r, url);
if (m) {
res.push(m);
} else if (r.index) {
res.push(createIndexMatch(r, [url], url.value));
}
}
return res;
}
function createIndexMatch(
r: Route, leftOverUrls: TreeNode<UrlSegment>[], lastUrlSegment: UrlSegment): MatchResult {
const outlet = r.outlet ? r.outlet : PRIMARY_OUTLET;
const children = r.children ? r.children : [];
return new MatchResult(
r.component, children, [], lastUrlSegment.parameters, leftOverUrls, [], outlet, r,
lastUrlSegment);
}
function matchIndex(
config: Route[], leftOverUrls: TreeNode<UrlSegment>[], lastUrlSegment: UrlSegment): MatchResult|
null {
for (let r of config) {
if (r.index) {
return createIndexMatch(r, leftOverUrls, lastUrlSegment);
}
}
return null;
}
function matchWithParts(route: Route, url: TreeNode<UrlSegment>): MatchResult|null {
if (!route.path) return null;
if ((route.outlet ? route.outlet : PRIMARY_OUTLET) !== url.value.outlet) return null;
const path = route.path.startsWith('/') ? route.path.substring(1) : route.path;
if (path === '**') {
const consumedUrl = [];
let u: TreeNode<UrlSegment>|null = url;
while (u) {
consumedUrl.push(u.value);
u = first(u.children);
}
const last = consumedUrl[consumedUrl.length - 1];
return new MatchResult(
route.component, [], consumedUrl, last.parameters, [], [], PRIMARY_OUTLET, route, last);
}
const m = match(route, url);
if (!m) return null;
const {consumedUrlSegments, lastSegment, lastParent, positionalParamSegments} = m;
const p = lastSegment.value.parameters;
const posParams = {};
forEach(positionalParamSegments, (v, k) => { posParams[k] = v.path; });
const parameters = <{[key: string]: string}>merge(p, posParams);
const secondarySubtrees = lastParent ? lastParent.children.slice(1) : [];
const children = route.children ? route.children : [];
const outlet = route.outlet ? route.outlet : PRIMARY_OUTLET;
return new MatchResult(
route.component, children, consumedUrlSegments, parameters, lastSegment.children,
secondarySubtrees, outlet, route, lastSegment.value);
}
class MatchResult {
constructor(
public component: Type|string, public children: Route[],
public consumedUrlSegments: UrlSegment[], public parameters: {[key: string]: string},
public leftOverUrl: TreeNode<UrlSegment>[], public secondary: TreeNode<UrlSegment>[],
public outlet: string, public route: Route|null, public lastUrlSegment: UrlSegment) {}
}