feat: implement recognizer

This commit is contained in:
vsavkin 2016-05-23 16:14:23 -07:00
parent 4b1db0e61c
commit f259a2204b
9 changed files with 561 additions and 5 deletions

View File

@ -60,7 +60,7 @@
"systemjs-builder": "^0.15.7",
"traceur": "0.0.96",
"tsd": "^0.6.5",
"typescript": "^1.9.0-dev.20160521-1.0",
"typescript": "^1.9.0-dev.20160409",
"typings": "^1.0.4",
"zone.js": "^0.6.6"
},

View File

@ -0,0 +1,12 @@
import { Type } from '@angular/core';
export type RouterConfig = Route[];
export interface Route {
name: string;
index?: boolean;
path?: string;
component: Type | string;
outlet?: string;
children?: Route[];
}

View File

@ -0,0 +1,188 @@
import { UrlTree, UrlSegment, equalUrlSegments } from './url_tree';
import { shallowEqual, flatten, first, merge } from './util';
import { TreeNode, rootNode } from './tree';
import { RouterState, ActivatedRoute, Params, PRIMARY_OUTLET } from './router_state';
import { RouterConfig, Route } from './config';
import { ComponentResolver, ComponentFactory, Type } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { Observer } from 'rxjs/Observer';
export function recognize(componentResolver: ComponentResolver, config: RouterConfig,
url: UrlTree, existingState: RouterState): Promise<RouterState> {
const match = new MatchResult(existingState.root.component, config, [url.root], {}, rootNode(url).children, [], PRIMARY_OUTLET);
return constructActivatedRoute(componentResolver, match, rootNode(existingState)).
then(roots => {
(<any>existingState.queryParams).next(url.queryParameters);
(<any>existingState.fragment).next(url.fragment);
return new RouterState(roots[0], existingState.queryParams, existingState.fragment);
});
}
function constructActivatedRoute(componentResolver: ComponentResolver, match: MatchResult,
existingRoute: TreeNode<ActivatedRoute> | null): Promise<TreeNode<ActivatedRoute>[]> {
//TODO: remove the cast after Angular is fixed
return componentResolver.resolveComponent(<any>match.component).then(factory => {
const activatedRoute = createOrReuseRoute(match, factory, existingRoute);
const existingChildren = existingRoute ? existingRoute.children : [];
if (match.leftOverUrl.length > 0) {
return recognizeMany(componentResolver, match.children, match.leftOverUrl, existingChildren)
.then(checkOutletNameUniqueness)
.then(children => [new TreeNode<ActivatedRoute>(activatedRoute, children)]);
} else {
return Promise.resolve([new TreeNode<ActivatedRoute>(activatedRoute, [])]);
}
});
}
function recognizeMany(componentResolver: ComponentResolver, config: Route[], urls: TreeNode<UrlSegment>[],
existingRoutes: TreeNode<ActivatedRoute>[]): Promise<TreeNode<ActivatedRoute>[]> {
const recognized = urls.map(url => recognizeOne(componentResolver, config, url, existingRoutes));
return Promise.all(<any>recognized).then(flatten);
}
function createOrReuseRoute(match: MatchResult, factory: ComponentFactory<any>, existing: TreeNode<ActivatedRoute> | null): ActivatedRoute {
if (existing) {
const v = existing.value;
if (v.component === match.component && v.outlet === match.outlet) {
(<any>(v.params)).next(match.parameters);
(<any>(v.urlSegments)).next(match.consumedUrlSegments);
return v;
}
}
return new ActivatedRoute(new BehaviorSubject(match.consumedUrlSegments), new BehaviorSubject(match.parameters), match.outlet,
factory.componentType, factory);
}
function recognizeOne(componentResolver: ComponentResolver, config: Route[],
url: TreeNode<UrlSegment>,
existingRoutes: TreeNode<ActivatedRoute>[]): Promise<TreeNode<ActivatedRoute>[]> {
let m;
try {
m = match(config, url);
} catch (e) {
return <any>Promise.reject(e);
}
const routesWithRightOutlet = existingRoutes.filter(r => r.value.outlet == m.outlet);
const routeWithRightOutlet = routesWithRightOutlet.length > 0 ? routesWithRightOutlet[0] : null;
const primary = constructActivatedRoute(componentResolver, m, routeWithRightOutlet);
const secondary = recognizeMany(componentResolver, config, m.secondary, existingRoutes);
return Promise.all([primary, secondary]).then(flatten).then(checkOutletNameUniqueness);
}
function checkOutletNameUniqueness(nodes: TreeNode<ActivatedRoute>[]): TreeNode<ActivatedRoute>[] {
let names = {};
nodes.forEach(n => {
let routeWithSameOutletName = names[n.value.outlet];
if (routeWithSameOutletName) {
const p = (<any>routeWithSameOutletName.urlSegments).value.map(s => s.toString()).join("/");
const c = (<any>n.value.urlSegments).value.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 match(config: Route[], url: TreeNode<UrlSegment>): MatchResult {
const m = matchNonIndex(config, url);
if (m) return m;
const mIndex = matchIndex(config, url);
if (mIndex) return mIndex;
const availableRoutes = config.map(r => `'${r.path}'`).join(", ");
throw new Error(
`Cannot match any routes. Current segment: '${url.value}'. Available routes: [${availableRoutes}].`);
}
function matchNonIndex(config: Route[], url: TreeNode<UrlSegment>): MatchResult | null {
for (let r of config) {
let m = matchWithParts(r, url);
if (m) return m;
}
return null;
}
function matchIndex(config: Route[], url: TreeNode<UrlSegment>): MatchResult | null {
for (let r of config) {
if (r.index) {
const outlet = r.outlet ? r.outlet : PRIMARY_OUTLET;
return new MatchResult(r.component, r.children, [], {}, [url], [], outlet);
}
}
return null;
}
function matchWithParts(route: Route, url: TreeNode<UrlSegment>): MatchResult | null {
if (!route.path) return null;
const path = route.path.startsWith("/") ? route.path.substring(1) : route.path;
if (path === "**") {
const consumedUrl = [];
let u = 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);
}
const parts = path.split("/");
const positionalParams = {};
const consumedUrlSegments = [];
let lastParent: TreeNode<UrlSegment>|null = null;
let lastSegment: TreeNode<UrlSegment>|null = null;
let current: TreeNode<UrlSegment>|null = url;
for (let i = 0; i < parts.length; ++i) {
if (!current) return null;
const p = parts[i];
const isLastSegment = i === parts.length - 1;
const isLastParent = i === parts.length - 2;
const isPosParam = p.startsWith(":");
if (!isPosParam && p != current.value.path) return null;
if (isLastSegment) {
lastSegment = current;
}
if (isLastParent) {
lastParent = current;
}
if (isPosParam) {
positionalParams[p.substring(1)] = current.value.path;
}
consumedUrlSegments.push(current.value);
current = first(current.children);
}
if (!lastSegment) throw "Cannot be reached";
const p = lastSegment.value.parameters;
const parameters = <{[key: string]: string}>merge(p, positionalParams);
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);
}
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
) {}
}

View File

@ -0,0 +1,33 @@
import { Tree, TreeNode } from './tree';
import { UrlSegment } from './url_tree';
import { Observable } from 'rxjs/Observable';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { ComponentFactory, Type } from '@angular/core';
export type Params = { [key: string]: string };
export const PRIMARY_OUTLET = "PRIMARY_OUTLET";
export class RouterState extends Tree<ActivatedRoute> {
constructor(root: TreeNode<ActivatedRoute>, public queryParams: Observable<Params>, public fragment: Observable<string>) {
super(root);
}
}
export function createEmptyState(rootComponent: Type): RouterState {
const emptyUrl = new BehaviorSubject([new UrlSegment("", {})]);
const emptyParams = new BehaviorSubject({});
const emptyQueryParams = new BehaviorSubject({});
const fragment = new BehaviorSubject("");
// TODO outlet name should not be outlet
const activated = new ActivatedRoute(emptyUrl, emptyParams, PRIMARY_OUTLET, rootComponent, <any>null);
return new RouterState(new TreeNode<ActivatedRoute>(activated, []), emptyQueryParams, fragment);
}
export class ActivatedRoute {
constructor(public urlSegments: Observable<UrlSegment[]>,
public params: Observable<Params>,
public outlet: string,
public component: Type,
public factory: ComponentFactory<any>) {}
}

View File

@ -54,7 +54,7 @@ function serializeChildren(node: TreeNode<UrlSegment>): string {
}
export function serializeSegment(segment: UrlSegment): string {
return `${segment.segment}${serializeParams(segment.parameters)}`;
return `${segment.path}${serializeParams(segment.parameters)}`;
}
function serializeParams(params: {[key: string]: string}): string {

View File

@ -1,4 +1,5 @@
import { Tree, TreeNode } from './tree';
import { shallowEqual } from './util';
export class UrlTree extends Tree<UrlSegment> {
constructor(root: TreeNode<UrlSegment>, public queryParameters: {[key: string]: string}, public fragment: string | null) {
@ -7,5 +8,25 @@ export class UrlTree extends Tree<UrlSegment> {
}
export class UrlSegment {
constructor(public segment: any, public parameters: {[key: string]: string}) {}
}
constructor(public path: string, public parameters: {[key: string]: string}) {}
toString() {
let params = [];
for (let prop in this.parameters) {
if (this.parameters.hasOwnProperty(prop)) {
params.push(`${prop}=${this.parameters[prop]}`);
}
}
const paramsString = params.length > 0 ? `(${params.join(',')})` : '';
return `${this.path}${paramsString}`;
}
}
export function equalUrlSegments(a: UrlSegment[], b: UrlSegment[]): boolean {
if (a.length !== b.length) return false;
for (let i = 0; i < a.length; ++i) {
if (a[i].path !== b[i].path) return false;
if (!shallowEqual(a[i].parameters, b[i].parameters)) return false;
}
return true;
}

View File

@ -0,0 +1,47 @@
export function shallowEqual(a: {[x:string]:any}, b: {[x:string]:any}): boolean {
var k1 = Object.keys(a);
var k2 = Object.keys(b);
if (k1.length != k2.length) {
return false;
}
var key;
for (var i = 0; i < k1.length; i++) {
key = k1[i];
if (a[key] !== b[key]) {
return false;
}
}
return true;
}
export function flatten<T>(a: T[][]): T[] {
const target = [];
for (let i = 0; i < a.length; ++i) {
for (let j = 0; j < a[i].length; ++j) {
target.push(a[i][j]);
}
}
return target;
}
export function first<T>(a: T[]): T | null {
return a.length > 0 ? a[0] : null;
}
export function merge<V>(m1: {[key: string]: V}, m2: {[key: string]: V}): {[key: string]: V} {
var m: {[key: string]: V} = {};
for (var attr in m1) {
if (m1.hasOwnProperty(attr)) {
m[attr] = m1[attr];
}
}
for (var attr in m2) {
if (m2.hasOwnProperty(attr)) {
m[attr] = m2[attr];
}
}
return m;
}

View File

@ -0,0 +1,255 @@
import {DefaultUrlSerializer} from '../src/url_serializer';
import {UrlTree} from '../src/url_tree';
import {createEmptyState, Params, ActivatedRoute, PRIMARY_OUTLET} from '../src/router_state';
import {recognize} from '../src/recognize';
describe('recognize', () => {
const empty = () => createEmptyState(RootComponent);
const fakeComponentResolver = {
resolveComponent(componentType:any):Promise<any> { return Promise.resolve({componentType}); },
clearCache() {}
};
it('should work', (done) => {
recognize(fakeComponentResolver, [
{
name: 'a',
path: 'a', component: ComponentA
}
], tree("a"), empty()).then(s => {
checkActivatedRoute(s.root, "", {}, RootComponent);
checkActivatedRoute(s.firstChild(s.root), "a", {}, ComponentA);
done();
});
});
it('should handle position args', (done) => {
recognize(fakeComponentResolver, [
{
name: 'a',
path: 'a/:id', component: ComponentA, children: [
{ name: 'b', path: 'b/:id', component: ComponentB}
]
}
], tree("a/paramA/b/paramB"), empty()).then(s => {
checkActivatedRoute(s.root, "", {}, RootComponent);
checkActivatedRoute(s.firstChild(s.root), "a/paramA", {id: 'paramA'}, ComponentA);
checkActivatedRoute(s.firstChild(<any>s.firstChild(s.root)), "b/paramB", {id: 'paramB'}, ComponentB);
done();
});
});
it('should reuse activated routes', (done) => {
const config = [{name: 'a', path: 'a/:id', component: ComponentA}];
recognize(fakeComponentResolver, config, tree("a/paramA"), empty()).then(s => {
const n1 = s.firstChild(s.root);
const recorded = [];
n1!.params.forEach(r => recorded.push(r));
recognize(fakeComponentResolver, config, tree("a/paramB"), s).then(s2 => {
const n2 = s2.firstChild(s2.root);
expect(n1).toBe(n2);
expect(recorded).toEqual([{id: 'paramA'}, {id: 'paramB'}]);
done();
});
});
});
it('should support secondary routes', (done) => {
recognize(fakeComponentResolver, [
{ name: 'a', path: 'a', component: ComponentA },
{ name: 'b', path: 'b', component: ComponentB, outlet: 'left' },
{ name: 'c', path: 'c', component: ComponentC, outlet: 'right' }
], tree("a(b//c)"), empty()).then(s => {
const c = s.children(s.root);
checkActivatedRoute(c[0], "a", {}, ComponentA);
checkActivatedRoute(c[1], "b", {}, ComponentB, 'left');
checkActivatedRoute(c[2], "c", {}, ComponentC, 'right');
done();
});
});
it('should handle nested secondary routes', (done) => {
recognize(fakeComponentResolver, [
{ name: 'a', path: 'a', component: ComponentA },
{ name: 'b', path: 'b', component: ComponentB, outlet: 'left' },
{ name: 'c', path: 'c', component: ComponentC, outlet: 'right' }
], tree("a(b(c))"), empty()).then(s => {
const c = s.children(s.root);
checkActivatedRoute(c[0], "a", {}, ComponentA);
checkActivatedRoute(c[1], "b", {}, ComponentB, 'left');
checkActivatedRoute(c[2], "c", {}, ComponentC, 'right');
done();
});
});
it('should handle non top-level secondary routes', (done) => {
recognize(fakeComponentResolver, [
{ name: 'a', path: 'a', component: ComponentA, children: [
{ name: 'b', path: 'b', component: ComponentB },
{ name: 'c', path: 'c', component: ComponentC, outlet: 'left' }
] },
], tree("a/b(c))"), empty()).then(s => {
const c = s.children(<any>s.firstChild(s.root));
checkActivatedRoute(c[0], "b", {}, ComponentB, PRIMARY_OUTLET);
checkActivatedRoute(c[1], "c", {}, ComponentC, 'left');
done();
});
});
it('should support matrix parameters', (done) => {
recognize(fakeComponentResolver, [
{
name: 'a',
path: 'a', component: ComponentA, children: [
{ name: 'b', path: 'b', component: ComponentB },
{ name: 'c', path: 'c', component: ComponentC, outlet: 'left' }
]
}
], tree("a;a1=11;a2=22/b;b1=111;b2=222(c;c1=1111;c2=2222)"), empty()).then(s => {
checkActivatedRoute(s.firstChild(s.root), "a", {a1: '11', a2: '22'}, ComponentA);
const c = s.children(<any>s.firstChild(s.root));
checkActivatedRoute(c[0], "b", {b1: '111', b2: '222'}, ComponentB);
checkActivatedRoute(c[1], "c", {c1: '1111', c2: '2222'}, ComponentC, 'left');
done();
});
});
describe("index", () => {
it("should support index routes", (done) => {
recognize(fakeComponentResolver, [
{
name: 'a', index: true, component: ComponentA
}
], tree(""), empty()).then(s => {
checkActivatedRoute(s.firstChild(s.root), "a", {}, ComponentA);
done();
});
});
it("should support index routes with children", (done) => {
recognize(fakeComponentResolver, [
{
name: 'a', index: true, component: ComponentA, children: [
{ name: 'b', index: true, component: ComponentB, children: [
{name: 'c', path: 'c/:id', component: ComponentC}
]
}
]
}
], tree("c/10"), empty()).then(s => {
checkActivatedRoute(s.firstChild(s.root), "", {}, ComponentA);
checkActivatedRoute(s.firstChild(<any>s.firstChild(s.root)), "", {}, ComponentB);
checkActivatedRoute(
s.firstChild(<any>s.firstChild(<any>s.firstChild(s.root))), "c/10", {id: '10'}, ComponentC);
done();
});
});
});
describe("wildcards", () => {
it("should support simple wildcards", (done) => {
recognize(fakeComponentResolver, [
{
name: 'a', path: '**', component: ComponentA
}
], tree("a/b/c/d;a1=11"), empty()).then(s => {
checkActivatedRoute(s.firstChild(s.root), "a/b/c/d", {a1:'11'}, ComponentA);
done();
});
});
});
describe("query parameters", () => {
it("should support query params", (done) => {
const config = [{name: 'a', path: 'a', component: ComponentA}];
recognize(fakeComponentResolver, config, tree("a?q=11"), empty()).then(s => {
const q1 = s.queryParams;
const recorded = [];
q1!.forEach(r => recorded.push(r));
recognize(fakeComponentResolver, config, tree("a?q=22"), s).then(s2 => {
const q2 = s2.queryParams;
expect(q1).toBe(q2);
expect(recorded).toEqual([{q: '11'}, {q: '22'}]);
done();
});
});
});
});
describe("fragment", () => {
it("should support fragment", (done) => {
const config = [{name: 'a', path: 'a', component: ComponentA}];
recognize(fakeComponentResolver, config, tree("a#f1"), empty()).then(s => {
const f1 = s.fragment;
const recorded = [];
f1!.forEach(r => recorded.push(r));
recognize(fakeComponentResolver, config, tree("a#f2"), s).then(s2 => {
const f2 = s2.fragment;
expect(f1).toBe(f2);
expect(recorded).toEqual(["f1", "f2"]);
done();
});
});
});
});
describe("error handling", () => {
it('should error when two routes with the same outlet name got matched', (done) => {
recognize(fakeComponentResolver, [
{ name: 'a', path: 'a', component: ComponentA },
{ name: 'b', path: 'b', component: ComponentB, outlet: 'aux' },
{ name: 'c', path: 'c', component: ComponentC, outlet: 'aux' }
], tree("a(b//c)"), empty()).catch(s => {
expect(s.toString()).toContain("Two segments cannot have the same outlet name: 'b' and 'c'.");
done();
});
});
it("should error when no matching routes", (done) => {
recognize(fakeComponentResolver, [
{ name: 'a', path: 'a', component: ComponentA }
], tree("invalid"), empty()).catch(s => {
expect(s.toString()).toContain("Cannot match any routes");
done();
});
});
it("should error when no matching routes (too short)", (done) => {
recognize(fakeComponentResolver, [
{ name: 'a', path: 'a/:id', component: ComponentA }
], tree("a"), empty()).catch(s => {
expect(s.toString()).toContain("Cannot match any routes");
done();
});
});
});
});
function checkActivatedRoute(actual: ActivatedRoute | null, url: string, params: Params, cmp: Function, outlet: string = PRIMARY_OUTLET):void {
if (actual === null) {
expect(actual).toBeDefined();
} else {
let actualUrl;
actual.urlSegments.forEach(segments => actualUrl = segments.map(s => s.path).join("/"));
expect(actualUrl).toEqual(url);
let actualParams;
actual.params.forEach(s => actualParams = s);
expect(actualParams).toEqual(params);
expect(actual.component).toBe(cmp);
expect(actual.outlet).toEqual(outlet);
}
}
function tree(url: string): UrlTree {
return new DefaultUrlSerializer().parse(url);
}
class RootComponent {}
class ComponentA {}
class ComponentB {}
class ComponentC {}

View File

@ -2,7 +2,6 @@
"compilerOptions": {
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"strictNullChecks": true,
"module": "commonjs",
"target": "es5",
"noImplicitAny": false,
@ -17,6 +16,7 @@
"src/router.ts",
"test/tree.spec.ts",
"test/url_serializer.spec.ts",
"test/recognize.spec.ts",
"test/router.spec.ts",
"typings/index.d.ts"
]