feat(router): add regex matchers

@petebacondarwin deserves credit for most of this commit.

This allows you to specify a regex and serializer function instead
of the path DSL in your route declaration.

```
@RouteConfig([
  { regex: '[a-z]+.[0-9]+',
    serializer: (params) => `{params.a}.params.b}`,
    component: MyComponent }
])
class Component {}
```

Closes #7325
Closes #7126
This commit is contained in:
Brian Ford 2016-02-09 11:12:41 -08:00 committed by Vikram Subramanian
parent 2548ce86db
commit 75343eb340
74 changed files with 986 additions and 738 deletions

View File

@ -4,17 +4,20 @@ var fs = require('fs');
var ts = require('typescript'); var ts = require('typescript');
var files = [ var files = [
'lifecycle_annotations_impl.ts', 'utils.ts',
'url_parser.ts', 'url_parser.ts',
'route_recognizer.ts', 'lifecycle/lifecycle_annotations_impl.ts',
'route_config_impl.ts', 'lifecycle/route_lifecycle_reflector.ts',
'async_route_handler.ts', 'route_config/route_config_impl.ts',
'sync_route_handler.ts', 'route_config/route_config_normalizer.ts',
'component_recognizer.ts', 'rules/route_handlers/async_route_handler.ts',
'rules/route_handlers/sync_route_handler.ts',
'rules/rules.ts',
'rules/rule_set.ts',
'rules/route_paths/route_path.ts',
'rules/route_paths/param_route_path.ts',
'rules/route_paths/regex_route_path.ts',
'instruction.ts', 'instruction.ts',
'path_recognizer.ts',
'route_config_nomalizer.ts',
'route_lifecycle_reflector.ts',
'route_registry.ts', 'route_registry.ts',
'router.ts' 'router.ts'
]; ];

View File

@ -200,7 +200,6 @@ function ngOutletFillContentDirective($compile) {
function routerTriggerDirective($q) { function routerTriggerDirective($q) {
return { return {
require: '^ngOutlet', require: '^ngOutlet',

View File

@ -351,7 +351,7 @@ describe('Navigation lifecycle', function () {
expect(spy).toHaveBeenCalled(); expect(spy).toHaveBeenCalled();
var args = spy.calls.mostRecent().args; var args = spy.calls.mostRecent().args;
expect(args[0].params).toEqual({name: 'brian'}); expect(args[0].params).toEqual(jasmine.objectContaining({name: 'brian'}));
expect(args[1]).toBe($http); expect(args[1]).toBe($http);
})); }));

View File

@ -15,7 +15,7 @@ import {MockAnimationBuilder} from 'angular2/src/mock/animation_builder_mock';
import {MockDirectiveResolver} from 'angular2/src/mock/directive_resolver_mock'; import {MockDirectiveResolver} from 'angular2/src/mock/directive_resolver_mock';
import {MockViewResolver} from 'angular2/src/mock/view_resolver_mock'; import {MockViewResolver} from 'angular2/src/mock/view_resolver_mock';
import {MockLocationStrategy} from 'angular2/src/mock/mock_location_strategy'; import {MockLocationStrategy} from 'angular2/src/mock/mock_location_strategy';
import {LocationStrategy} from 'angular2/src/router/location_strategy'; import {LocationStrategy} from 'angular2/src/router/location/location_strategy';
import {MockNgZone} from 'angular2/src/mock/ng_zone_mock'; import {MockNgZone} from 'angular2/src/mock/ng_zone_mock';
import {XHRImpl} from "angular2/src/platform/browser/xhr_impl"; import {XHRImpl} from "angular2/src/platform/browser/xhr_impl";

View File

@ -16,7 +16,7 @@ import {MockAnimationBuilder} from 'angular2/src/mock/animation_builder_mock';
import {MockDirectiveResolver} from 'angular2/src/mock/directive_resolver_mock'; import {MockDirectiveResolver} from 'angular2/src/mock/directive_resolver_mock';
import {MockViewResolver} from 'angular2/src/mock/view_resolver_mock'; import {MockViewResolver} from 'angular2/src/mock/view_resolver_mock';
import {MockLocationStrategy} from 'angular2/src/mock/mock_location_strategy'; import {MockLocationStrategy} from 'angular2/src/mock/mock_location_strategy';
import {LocationStrategy} from 'angular2/src/router/location_strategy'; import {LocationStrategy} from 'angular2/src/router/location/location_strategy';
import {MockNgZone} from 'angular2/src/mock/ng_zone_mock'; import {MockNgZone} from 'angular2/src/mock/ng_zone_mock';
import {TestComponentBuilder} from 'angular2/src/testing/test_component_builder'; import {TestComponentBuilder} from 'angular2/src/testing/test_component_builder';

View File

@ -5,26 +5,26 @@
*/ */
export {Router} from './src/router/router'; export {Router} from './src/router/router';
export {RouterOutlet} from './src/router/router_outlet'; export {RouterOutlet} from './src/router/directives/router_outlet';
export {RouterLink} from './src/router/router_link'; export {RouterLink} from './src/router/directives/router_link';
export {RouteParams, RouteData} from './src/router/instruction'; export {RouteParams, RouteData} from './src/router/instruction';
export {PlatformLocation} from './src/router/platform_location'; export {PlatformLocation} from './src/router/location/platform_location';
export {RouteRegistry, ROUTER_PRIMARY_COMPONENT} from './src/router/route_registry'; export {RouteRegistry, ROUTER_PRIMARY_COMPONENT} from './src/router/route_registry';
export {LocationStrategy, APP_BASE_HREF} from './src/router/location_strategy'; export {LocationStrategy, APP_BASE_HREF} from './src/router/location/location_strategy';
export {HashLocationStrategy} from './src/router/hash_location_strategy'; export {HashLocationStrategy} from './src/router/location/hash_location_strategy';
export {PathLocationStrategy} from './src/router/path_location_strategy'; export {PathLocationStrategy} from './src/router/location/path_location_strategy';
export {Location} from './src/router/location'; export {Location} from './src/router/location/location';
export * from './src/router/route_config_decorator'; export * from './src/router/route_config/route_config_decorator';
export * from './src/router/route_definition'; export * from './src/router/route_definition';
export {OnActivate, OnDeactivate, OnReuse, CanDeactivate, CanReuse} from './src/router/interfaces'; export {OnActivate, OnDeactivate, OnReuse, CanDeactivate, CanReuse} from './src/router/interfaces';
export {CanActivate} from './src/router/lifecycle_annotations'; export {CanActivate} from './src/router/lifecycle/lifecycle_annotations';
export {Instruction, ComponentInstruction} from './src/router/instruction'; export {Instruction, ComponentInstruction} from './src/router/instruction';
export {OpaqueToken} from 'angular2/core'; export {OpaqueToken} from 'angular2/core';
export {ROUTER_PROVIDERS_COMMON} from 'angular2/src/router/router_providers_common'; export {ROUTER_PROVIDERS_COMMON} from 'angular2/src/router/router_providers_common';
export {ROUTER_PROVIDERS, ROUTER_BINDINGS} from 'angular2/src/router/router_providers'; export {ROUTER_PROVIDERS, ROUTER_BINDINGS} from 'angular2/src/router/router_providers';
import {RouterOutlet} from './src/router/router_outlet'; import {RouterOutlet} from './src/router/directives/router_outlet';
import {RouterLink} from './src/router/router_link'; import {RouterLink} from './src/router/directives/router_link';
import {CONST_EXPR} from './src/facade/lang'; import {CONST_EXPR} from './src/facade/lang';
/** /**

View File

@ -1,9 +1,9 @@
import {TEMPLATE_TRANSFORMS} from 'angular2/compiler'; import {TEMPLATE_TRANSFORMS} from 'angular2/compiler';
import {Provider} from 'angular2/core'; import {Provider} from 'angular2/core';
import {RouterLinkTransform} from 'angular2/src/router/router_link_transform'; import {RouterLinkTransform} from 'angular2/src/router/directives/router_link_transform';
import {CONST_EXPR} from 'angular2/src/facade/lang'; import {CONST_EXPR} from 'angular2/src/facade/lang';
export {RouterLinkTransform} from 'angular2/src/router/router_link_transform'; export {RouterLinkTransform} from 'angular2/src/router/directives/router_link_transform';
/** /**
* Enables the router link DSL. * Enables the router link DSL.

View File

@ -1,7 +1,7 @@
import {Injectable} from 'angular2/src/core/di'; import {Injectable} from 'angular2/src/core/di';
import {EventEmitter, ObservableWrapper} from 'angular2/src/facade/async'; import {EventEmitter, ObservableWrapper} from 'angular2/src/facade/async';
import {ListWrapper} from 'angular2/src/facade/collection'; import {ListWrapper} from 'angular2/src/facade/collection';
import {Location} from 'angular2/src/router/location'; import {Location} from 'angular2/src/router/location/location';
/** /**
* A spy for {@link Location} that allows tests to fire simulated location events. * A spy for {@link Location} that allows tests to fire simulated location events.

View File

@ -1,6 +1,6 @@
import {Injectable} from 'angular2/src/core/di'; import {Injectable} from 'angular2/src/core/di';
import {EventEmitter, ObservableWrapper} from 'angular2/src/facade/async'; import {EventEmitter, ObservableWrapper} from 'angular2/src/facade/async';
import {LocationStrategy} from 'angular2/src/router/location_strategy'; import {LocationStrategy} from 'angular2/src/router/location/location_strategy';
/** /**

View File

@ -36,7 +36,7 @@ import {BrowserDomAdapter} from './browser/browser_adapter';
import {wtfInit} from 'angular2/src/core/profile/wtf_init'; import {wtfInit} from 'angular2/src/core/profile/wtf_init';
import {MessageBasedRenderer} from 'angular2/src/web_workers/ui/renderer'; import {MessageBasedRenderer} from 'angular2/src/web_workers/ui/renderer';
import {MessageBasedXHRImpl} from 'angular2/src/web_workers/ui/xhr_impl'; import {MessageBasedXHRImpl} from 'angular2/src/web_workers/ui/xhr_impl';
import {BrowserPlatformLocation} from 'angular2/src/router/browser_platform_location'; import {BrowserPlatformLocation} from 'angular2/src/router/location/browser_platform_location';
import { import {
ServiceMessageBrokerFactory, ServiceMessageBrokerFactory,
ServiceMessageBrokerFactory_ ServiceMessageBrokerFactory_

View File

@ -1,163 +0,0 @@
import {isBlank, isPresent} from 'angular2/src/facade/lang';
import {BaseException, WrappedException} from 'angular2/src/facade/exceptions';
import {Map, MapWrapper, ListWrapper, StringMapWrapper} from 'angular2/src/facade/collection';
import {PromiseWrapper} from 'angular2/src/facade/async';
import {
AbstractRecognizer,
RouteRecognizer,
RedirectRecognizer,
RouteMatch,
PathMatch
} from './route_recognizer';
import {Route, AsyncRoute, AuxRoute, Redirect, RouteDefinition} from './route_config_impl';
import {AsyncRouteHandler} from './async_route_handler';
import {SyncRouteHandler} from './sync_route_handler';
import {Url} from './url_parser';
import {ComponentInstruction} from './instruction';
/**
* `ComponentRecognizer` is responsible for recognizing routes for a single component.
* It is consumed by `RouteRegistry`, which knows how to recognize an entire hierarchy of
* components.
*/
export class ComponentRecognizer {
names = new Map<string, RouteRecognizer>();
// map from name to recognizer
auxNames = new Map<string, RouteRecognizer>();
// map from starting path to recognizer
auxRoutes = new Map<string, RouteRecognizer>();
// TODO: optimize this into a trie
matchers: AbstractRecognizer[] = [];
defaultRoute: RouteRecognizer = null;
/**
* returns whether or not the config is terminal
*/
config(config: RouteDefinition): boolean {
var handler;
if (isPresent(config.name) && config.name[0].toUpperCase() != config.name[0]) {
var suggestedName = config.name[0].toUpperCase() + config.name.substring(1);
throw new BaseException(
`Route "${config.path}" with name "${config.name}" does not begin with an uppercase letter. Route names should be CamelCase like "${suggestedName}".`);
}
if (config instanceof AuxRoute) {
handler = new SyncRouteHandler(config.component, config.data);
let path = config.path.startsWith('/') ? config.path.substring(1) : config.path;
var recognizer = new RouteRecognizer(config.path, handler);
this.auxRoutes.set(path, recognizer);
if (isPresent(config.name)) {
this.auxNames.set(config.name, recognizer);
}
return recognizer.terminal;
}
var useAsDefault = false;
if (config instanceof Redirect) {
let redirector = new RedirectRecognizer(config.path, config.redirectTo);
this._assertNoHashCollision(redirector.hash, config.path);
this.matchers.push(redirector);
return true;
}
if (config instanceof Route) {
handler = new SyncRouteHandler(config.component, config.data);
useAsDefault = isPresent(config.useAsDefault) && config.useAsDefault;
} else if (config instanceof AsyncRoute) {
handler = new AsyncRouteHandler(config.loader, config.data);
useAsDefault = isPresent(config.useAsDefault) && config.useAsDefault;
}
var recognizer = new RouteRecognizer(config.path, handler);
this._assertNoHashCollision(recognizer.hash, config.path);
if (useAsDefault) {
if (isPresent(this.defaultRoute)) {
throw new BaseException(`Only one route can be default`);
}
this.defaultRoute = recognizer;
}
this.matchers.push(recognizer);
if (isPresent(config.name)) {
this.names.set(config.name, recognizer);
}
return recognizer.terminal;
}
private _assertNoHashCollision(hash: string, path) {
this.matchers.forEach((matcher) => {
if (hash == matcher.hash) {
throw new BaseException(
`Configuration '${path}' conflicts with existing route '${matcher.path}'`);
}
});
}
/**
* Given a URL, returns a list of `RouteMatch`es, which are partial recognitions for some route.
*/
recognize(urlParse: Url): Promise<RouteMatch>[] {
var solutions = [];
this.matchers.forEach((routeRecognizer: AbstractRecognizer) => {
var pathMatch = routeRecognizer.recognize(urlParse);
if (isPresent(pathMatch)) {
solutions.push(pathMatch);
}
});
// handle cases where we are routing just to an aux route
if (solutions.length == 0 && isPresent(urlParse) && urlParse.auxiliary.length > 0) {
return [PromiseWrapper.resolve(new PathMatch(null, null, urlParse.auxiliary))];
}
return solutions;
}
recognizeAuxiliary(urlParse: Url): Promise<RouteMatch>[] {
var routeRecognizer: RouteRecognizer = this.auxRoutes.get(urlParse.path);
if (isPresent(routeRecognizer)) {
return [routeRecognizer.recognize(urlParse)];
}
return [PromiseWrapper.resolve(null)];
}
hasRoute(name: string): boolean { return this.names.has(name); }
componentLoaded(name: string): boolean {
return this.hasRoute(name) && isPresent(this.names.get(name).handler.componentType);
}
loadComponent(name: string): Promise<any> {
return this.names.get(name).handler.resolveComponentType();
}
generate(name: string, params: any): ComponentInstruction {
var pathRecognizer: RouteRecognizer = this.names.get(name);
if (isBlank(pathRecognizer)) {
return null;
}
return pathRecognizer.generate(params);
}
generateAuxiliary(name: string, params: any): ComponentInstruction {
var pathRecognizer: RouteRecognizer = this.auxNames.get(name);
if (isBlank(pathRecognizer)) {
return null;
}
return pathRecognizer.generate(params);
}
}

View File

@ -1,9 +1,9 @@
import {Directive} from 'angular2/core'; import {Directive} from 'angular2/core';
import {isString} from 'angular2/src/facade/lang'; import {isString} from 'angular2/src/facade/lang';
import {Router} from './router'; import {Router} from '../router';
import {Location} from './location'; import {Location} from '../location/location';
import {Instruction} from './instruction'; import {Instruction} from '../instruction';
/** /**
* The RouterLink directive lets you link to specific parts of your app. * The RouterLink directive lets you link to specific parts of your app.

View File

@ -14,11 +14,11 @@ import {
Dependency Dependency
} from 'angular2/core'; } from 'angular2/core';
import * as routerMod from './router'; import * as routerMod from '../router';
import {ComponentInstruction, RouteParams, RouteData} from './instruction'; import {ComponentInstruction, RouteParams, RouteData} from '../instruction';
import * as hookMod from './lifecycle_annotations'; import * as hookMod from '../lifecycle/lifecycle_annotations';
import {hasLifecycleHook} from './route_lifecycle_reflector'; import {hasLifecycleHook} from '../lifecycle/route_lifecycle_reflector';
import {OnActivate, CanReuse, OnReuse, OnDeactivate, CanDeactivate} from './interfaces'; import {OnActivate, CanReuse, OnReuse, OnDeactivate, CanDeactivate} from '../interfaces';
let _resolveToTrue = PromiseWrapper.resolve(true); let _resolveToTrue = PromiseWrapper.resolve(true);

View File

@ -224,15 +224,11 @@ export class ResolvedInstruction extends Instruction {
/** /**
* Represents a resolved default route * Represents a resolved default route
*/ */
export class DefaultInstruction extends Instruction { export class DefaultInstruction extends ResolvedInstruction {
constructor(component: ComponentInstruction, child: DefaultInstruction) { constructor(component: ComponentInstruction, child: DefaultInstruction) {
super(component, child, {}); super(component, child, {});
} }
resolveComponent(): Promise<ComponentInstruction> {
return PromiseWrapper.resolve(this.component);
}
toLinkUrl(): string { return ''; } toLinkUrl(): string { return ''; }
/** @internal */ /** @internal */
@ -292,8 +288,7 @@ export class RedirectInstruction extends ResolvedInstruction {
/** /**
* A `ComponentInstruction` represents the route state for a single component. An `Instruction` is * A `ComponentInstruction` represents the route state for a single component.
* composed of a tree of these `ComponentInstruction`s.
* *
* `ComponentInstructions` is a public API. Instances of `ComponentInstruction` are passed * `ComponentInstructions` is a public API. Instances of `ComponentInstruction` are passed
* to route lifecycle hooks, like {@link CanActivate}. * to route lifecycle hooks, like {@link CanActivate}.
@ -308,6 +303,9 @@ export class ComponentInstruction {
reuse: boolean = false; reuse: boolean = false;
public routeData: RouteData; public routeData: RouteData;
/**
* @internal
*/
constructor(public urlPath: string, public urlParams: string[], data: RouteData, constructor(public urlPath: string, public urlParams: string[], data: RouteData,
public componentType, public terminal: boolean, public specificity: string, public componentType, public terminal: boolean, public specificity: string,
public params: {[key: string]: any} = null) { public params: {[key: string]: any} = null) {

View File

@ -5,7 +5,7 @@
import {makeDecorator} from 'angular2/src/core/util/decorators'; import {makeDecorator} from 'angular2/src/core/util/decorators';
import {CanActivate as CanActivateAnnotation} from './lifecycle_annotations_impl'; import {CanActivate as CanActivateAnnotation} from './lifecycle_annotations_impl';
import {ComponentInstruction} from './instruction'; import {ComponentInstruction} from '../instruction';
export { export {
routerCanReuse, routerCanReuse,

View File

@ -1,6 +1,6 @@
library angular.router.route_lifecycle_reflector; library angular.router.route_lifecycle_reflector;
import 'package:angular2/src/router/lifecycle_annotations_impl.dart'; import 'package:angular2/src/router/lifecycle/lifecycle_annotations_impl.dart';
import 'package:angular2/src/router/interfaces.dart'; import 'package:angular2/src/router/interfaces.dart';
import 'package:angular2/src/core/reflection/reflection.dart'; import 'package:angular2/src/core/reflection/reflection.dart';

View File

@ -1,281 +0,0 @@
import {
RegExp,
RegExpWrapper,
RegExpMatcherWrapper,
StringWrapper,
isPresent,
isBlank
} from 'angular2/src/facade/lang';
import {BaseException, WrappedException} from 'angular2/src/facade/exceptions';
import {Map, MapWrapper, StringMapWrapper} from 'angular2/src/facade/collection';
import {Url, RootUrl, serializeParams} from './url_parser';
class TouchMap {
map: {[key: string]: string} = {};
keys: {[key: string]: boolean} = {};
constructor(map: {[key: string]: any}) {
if (isPresent(map)) {
StringMapWrapper.forEach(map, (value, key) => {
this.map[key] = isPresent(value) ? value.toString() : null;
this.keys[key] = true;
});
}
}
get(key: string): string {
StringMapWrapper.delete(this.keys, key);
return this.map[key];
}
getUnused(): {[key: string]: any} {
var unused: {[key: string]: any} = {};
var keys = StringMapWrapper.keys(this.keys);
keys.forEach(key => unused[key] = StringMapWrapper.get(this.map, key));
return unused;
}
}
function normalizeString(obj: any): string {
if (isBlank(obj)) {
return null;
} else {
return obj.toString();
}
}
interface Segment {
name: string;
generate(params: TouchMap): string;
match(path: string): boolean;
}
class ContinuationSegment implements Segment {
name: string = '';
generate(params: TouchMap): string { return ''; }
match(path: string): boolean { return true; }
}
class StaticSegment implements Segment {
name: string = '';
constructor(public path: string) {}
match(path: string): boolean { return path == this.path; }
generate(params: TouchMap): string { return this.path; }
}
class DynamicSegment implements Segment {
constructor(public name: string) {}
match(path: string): boolean { return path.length > 0; }
generate(params: TouchMap): string {
if (!StringMapWrapper.contains(params.map, this.name)) {
throw new BaseException(
`Route generator for '${this.name}' was not included in parameters passed.`);
}
return normalizeString(params.get(this.name));
}
}
class StarSegment implements Segment {
constructor(public name: string) {}
match(path: string): boolean { return true; }
generate(params: TouchMap): string { return normalizeString(params.get(this.name)); }
}
var paramMatcher = /^:([^\/]+)$/g;
var wildcardMatcher = /^\*([^\/]+)$/g;
function parsePathString(route: string): {[key: string]: any} {
// normalize route as not starting with a "/". Recognition will
// also normalize.
if (route.startsWith("/")) {
route = route.substring(1);
}
var segments = splitBySlash(route);
var results = [];
var specificity = '';
// a single slash (or "empty segment" is as specific as a static segment
if (segments.length == 0) {
specificity += '2';
}
// The "specificity" of a path is used to determine which route is used when multiple routes match
// a URL. Static segments (like "/foo") are the most specific, followed by dynamic segments (like
// "/:id"). Star segments add no specificity. Segments at the start of the path are more specific
// than proceeding ones.
//
// The code below uses place values to combine the different types of segments into a single
// string that we can sort later. Each static segment is marked as a specificity of "2," each
// dynamic segment is worth "1" specificity, and stars are worth "0" specificity.
var limit = segments.length - 1;
for (var i = 0; i <= limit; i++) {
var segment = segments[i], match;
if (isPresent(match = RegExpWrapper.firstMatch(paramMatcher, segment))) {
results.push(new DynamicSegment(match[1]));
specificity += '1';
} else if (isPresent(match = RegExpWrapper.firstMatch(wildcardMatcher, segment))) {
results.push(new StarSegment(match[1]));
specificity += '0';
} else if (segment == '...') {
if (i < limit) {
throw new BaseException(`Unexpected "..." before the end of the path for "${route}".`);
}
results.push(new ContinuationSegment());
} else {
results.push(new StaticSegment(segment));
specificity += '2';
}
}
return {'segments': results, 'specificity': specificity};
}
// this function is used to determine whether a route config path like `/foo/:id` collides with
// `/foo/:name`
function pathDslHash(segments: Segment[]): string {
return segments.map((segment) => {
if (segment instanceof StarSegment) {
return '*';
} else if (segment instanceof ContinuationSegment) {
return '...';
} else if (segment instanceof DynamicSegment) {
return ':';
} else if (segment instanceof StaticSegment) {
return segment.path;
}
})
.join('/');
}
function splitBySlash(url: string): string[] {
return url.split('/');
}
var RESERVED_CHARS = RegExpWrapper.create('//|\\(|\\)|;|\\?|=');
function assertPath(path: string) {
if (StringWrapper.contains(path, '#')) {
throw new BaseException(
`Path "${path}" should not include "#". Use "HashLocationStrategy" instead.`);
}
var illegalCharacter = RegExpWrapper.firstMatch(RESERVED_CHARS, path);
if (isPresent(illegalCharacter)) {
throw new BaseException(
`Path "${path}" contains "${illegalCharacter[0]}" which is not allowed in a route config.`);
}
}
/**
* Parses a URL string using a given matcher DSL, and generates URLs from param maps
*/
export class PathRecognizer {
private _segments: Segment[];
specificity: string;
terminal: boolean = true;
hash: string;
constructor(public path: string) {
assertPath(path);
var parsed = parsePathString(path);
this._segments = parsed['segments'];
this.specificity = parsed['specificity'];
this.hash = pathDslHash(this._segments);
var lastSegment = this._segments[this._segments.length - 1];
this.terminal = !(lastSegment instanceof ContinuationSegment);
}
recognize(beginningSegment: Url): {[key: string]: any} {
var nextSegment = beginningSegment;
var currentSegment: Url;
var positionalParams = {};
var captured = [];
for (var i = 0; i < this._segments.length; i += 1) {
var segment = this._segments[i];
currentSegment = nextSegment;
if (segment instanceof ContinuationSegment) {
break;
}
if (isPresent(currentSegment)) {
// the star segment consumes all of the remaining URL, including matrix params
if (segment instanceof StarSegment) {
positionalParams[segment.name] = currentSegment.toString();
captured.push(currentSegment.toString());
nextSegment = null;
break;
}
captured.push(currentSegment.path);
if (segment instanceof DynamicSegment) {
positionalParams[segment.name] = currentSegment.path;
} else if (!segment.match(currentSegment.path)) {
return null;
}
nextSegment = currentSegment.child;
} else if (!segment.match('')) {
return null;
}
}
if (this.terminal && isPresent(nextSegment)) {
return null;
}
var urlPath = captured.join('/');
var auxiliary;
var urlParams;
var allParams;
if (isPresent(currentSegment)) {
// If this is the root component, read query params. Otherwise, read matrix params.
var paramsSegment = beginningSegment instanceof RootUrl ? beginningSegment : currentSegment;
allParams = isPresent(paramsSegment.params) ?
StringMapWrapper.merge(paramsSegment.params, positionalParams) :
positionalParams;
urlParams = serializeParams(paramsSegment.params);
auxiliary = currentSegment.auxiliary;
} else {
allParams = positionalParams;
auxiliary = [];
urlParams = [];
}
return {urlPath, urlParams, allParams, auxiliary, nextSegment};
}
generate(params: {[key: string]: any}): {[key: string]: any} {
var paramTokens = new TouchMap(params);
var path = [];
for (var i = 0; i < this._segments.length; i++) {
let segment = this._segments[i];
if (!(segment instanceof ContinuationSegment)) {
path.push(segment.generate(paramTokens));
}
}
var urlPath = path.join('/');
var nonPositionalParams = paramTokens.getUnused();
var urlParams = serializeParams(nonPositionalParams);
return {urlPath, urlParams};
}
}

View File

@ -1,6 +1,8 @@
import {CONST, Type, isPresent} from 'angular2/src/facade/lang'; import {CONST, Type, isPresent} from 'angular2/src/facade/lang';
import {RouteDefinition} from './route_definition'; import {RouteDefinition} from '../route_definition';
export {RouteDefinition} from './route_definition'; import {RegexSerializer} from '../rules/route_paths/regex_route_path';
export {RouteDefinition} from '../route_definition';
/** /**
* The `RouteConfig` decorator defines routes for a given component. * The `RouteConfig` decorator defines routes for a given component.
@ -12,6 +14,25 @@ export class RouteConfig {
constructor(public configs: RouteDefinition[]) {} constructor(public configs: RouteDefinition[]) {}
} }
@CONST()
export abstract class AbstractRoute implements RouteDefinition {
name: string;
useAsDefault: boolean;
path: string;
regex: string;
serializer: RegexSerializer;
data: {[key: string]: any};
constructor({name, useAsDefault, path, regex, serializer, data}: RouteDefinition) {
this.name = name;
this.useAsDefault = useAsDefault;
this.path = path;
this.regex = regex;
this.serializer = serializer;
this.data = data;
}
}
/** /**
* `Route` is a type of {@link RouteDefinition} used to route a path to a component. * `Route` is a type of {@link RouteDefinition} used to route a path to a component.
* *
@ -35,25 +56,20 @@ export class RouteConfig {
* ``` * ```
*/ */
@CONST() @CONST()
export class Route implements RouteDefinition { export class Route extends AbstractRoute {
data: {[key: string]: any}; component: any;
path: string;
component: Type;
name: string;
useAsDefault: boolean;
// added next three properties to work around https://github.com/Microsoft/TypeScript/issues/4107
aux: string = null; aux: string = null;
loader: Function = null;
redirectTo: any[] = null; constructor({name, useAsDefault, path, regex, serializer, data, component}: RouteDefinition) {
constructor({path, component, name, data, useAsDefault}: { super({
path: string, name: name,
component: Type, name?: string, data?: {[key: string]: any}, useAsDefault?: boolean useAsDefault: useAsDefault,
}) { path: path,
this.path = path; regex: regex,
serializer: serializer,
data: data
});
this.component = component; this.component = component;
this.name = name;
this.data = data;
this.useAsDefault = useAsDefault;
} }
} }
@ -78,20 +94,19 @@ export class Route implements RouteDefinition {
* ``` * ```
*/ */
@CONST() @CONST()
export class AuxRoute implements RouteDefinition { export class AuxRoute extends AbstractRoute {
data: {[key: string]: any} = null; component: any;
path: string;
component: Type; constructor({name, useAsDefault, path, regex, serializer, data, component}: RouteDefinition) {
name: string; super({
// added next three properties to work around https://github.com/Microsoft/TypeScript/issues/4107 name: name,
aux: string = null; useAsDefault: useAsDefault,
loader: Function = null; path: path,
redirectTo: any[] = null; regex: regex,
useAsDefault: boolean = false; serializer: serializer,
constructor({path, component, name}: {path: string, component: Type, name?: string}) { data: data
this.path = path; });
this.component = component; this.component = component;
this.name = name;
} }
} }
@ -120,22 +135,20 @@ export class AuxRoute implements RouteDefinition {
* ``` * ```
*/ */
@CONST() @CONST()
export class AsyncRoute implements RouteDefinition { export class AsyncRoute extends AbstractRoute {
data: {[key: string]: any};
path: string;
loader: Function; loader: Function;
name: string;
useAsDefault: boolean;
aux: string = null; aux: string = null;
constructor({path, loader, name, data, useAsDefault}: {
path: string, constructor({name, useAsDefault, path, regex, serializer, data, loader}: RouteDefinition) {
loader: Function, name?: string, data?: {[key: string]: any}, useAsDefault?: boolean super({
}) { name: name,
this.path = path; useAsDefault: useAsDefault,
path: path,
regex: regex,
serializer: serializer,
data: data
});
this.loader = loader; this.loader = loader;
this.name = name;
this.data = data;
this.useAsDefault = useAsDefault;
} }
} }
@ -161,17 +174,18 @@ export class AsyncRoute implements RouteDefinition {
* ``` * ```
*/ */
@CONST() @CONST()
export class Redirect implements RouteDefinition { export class Redirect extends AbstractRoute {
path: string;
redirectTo: any[]; redirectTo: any[];
name: string = null;
// added next three properties to work around https://github.com/Microsoft/TypeScript/issues/4107 constructor({name, useAsDefault, path, regex, serializer, data, redirectTo}: RouteDefinition) {
loader: Function = null; super({
data: any = null; name: name,
aux: string = null; useAsDefault: useAsDefault,
useAsDefault: boolean = false; path: path,
constructor({path, redirectTo}: {path: string, redirectTo: any[]}) { regex: regex,
this.path = path; serializer: serializer,
data: data
});
this.redirectTo = redirectTo; this.redirectTo = redirectTo;
} }
} }

View File

@ -1,7 +1,9 @@
library angular2.src.router.route_config_normalizer; library angular2.src.router.route_config_normalizer;
import "route_config_decorator.dart"; import "route_config_decorator.dart";
import "route_registry.dart"; import "../route_definition.dart";
import "../route_registry.dart";
import "package:angular2/src/facade/lang.dart";
import "package:angular2/src/facade/exceptions.dart" show BaseException; import "package:angular2/src/facade/exceptions.dart" show BaseException;
RouteDefinition normalizeRouteConfig(RouteDefinition config, RouteRegistry registry) { RouteDefinition normalizeRouteConfig(RouteDefinition config, RouteRegistry registry) {

View File

@ -1,8 +1,8 @@
import {AsyncRoute, AuxRoute, Route, Redirect, RouteDefinition} from './route_config_decorator'; import {AsyncRoute, AuxRoute, Route, Redirect, RouteDefinition} from './route_config_decorator';
import {ComponentDefinition} from './route_definition'; import {ComponentDefinition} from '../route_definition';
import {isType, Type} from 'angular2/src/facade/lang'; import {isType, Type} from 'angular2/src/facade/lang';
import {BaseException, WrappedException} from 'angular2/src/facade/exceptions'; import {BaseException, WrappedException} from 'angular2/src/facade/exceptions';
import {RouteRegistry} from './route_registry'; import {RouteRegistry} from '../route_registry';
/** /**

View File

@ -4,5 +4,7 @@ abstract class RouteDefinition {
final String path; final String path;
final String name; final String name;
final bool useAsDefault; final bool useAsDefault;
const RouteDefinition({this.path, this.name, this.useAsDefault : false}); final String regex;
final Function serializer;
const RouteDefinition({this.path, this.name, this.useAsDefault : false, this.regex, this.serializer});
} }

View File

@ -1,4 +1,5 @@
import {CONST, Type} from 'angular2/src/facade/lang'; import {CONST, Type} from 'angular2/src/facade/lang';
import {RegexSerializer} from './rules/route_paths/regex_route_path';
/** /**
* `RouteDefinition` defines a route within a {@link RouteConfig} decorator. * `RouteDefinition` defines a route within a {@link RouteConfig} decorator.
@ -14,6 +15,8 @@ import {CONST, Type} from 'angular2/src/facade/lang';
export interface RouteDefinition { export interface RouteDefinition {
path?: string; path?: string;
aux?: string; aux?: string;
regex?: string;
serializer?: RegexSerializer;
component?: Type | ComponentDefinition; component?: Type | ComponentDefinition;
loader?: Function; loader?: Function;
redirectTo?: any[]; redirectTo?: any[];

View File

@ -24,9 +24,9 @@ import {
AuxRoute, AuxRoute,
Redirect, Redirect,
RouteDefinition RouteDefinition
} from './route_config_impl'; } from './route_config/route_config_impl';
import {PathMatch, RedirectMatch, RouteMatch} from './route_recognizer'; import {PathMatch, RedirectMatch, RouteMatch} from './rules/rules';
import {ComponentRecognizer} from './component_recognizer'; import {RuleSet} from './rules/rule_set';
import { import {
Instruction, Instruction,
ResolvedInstruction, ResolvedInstruction,
@ -35,12 +35,20 @@ import {
DefaultInstruction DefaultInstruction
} from './instruction'; } from './instruction';
import {normalizeRouteConfig, assertComponentExists} from './route_config_nomalizer'; import {normalizeRouteConfig, assertComponentExists} from './route_config/route_config_normalizer';
import {parser, Url, pathSegmentsToUrl} from './url_parser'; import {parser, Url, convertUrlParamsToArray, pathSegmentsToUrl} from './url_parser';
var _resolveToNull = PromiseWrapper.resolve(null); var _resolveToNull = PromiseWrapper.resolve(null);
// A LinkItemArray is an array, which describes a set of routes
// The items in the array are found in groups:
// - the first item is the name of the route
// - the next items are:
// - an object containing parameters
// - or an array describing an aux route
// export type LinkRouteItem = string | Object;
// export type LinkItem = LinkRouteItem | Array<LinkRouteItem>;
// export type LinkItemArray = Array<LinkItem>;
/** /**
* Token used to bind the component with the top-level {@link RouteConfig}s for the * Token used to bind the component with the top-level {@link RouteConfig}s for the
@ -78,7 +86,7 @@ export const ROUTER_PRIMARY_COMPONENT: OpaqueToken =
*/ */
@Injectable() @Injectable()
export class RouteRegistry { export class RouteRegistry {
private _rules = new Map<any, ComponentRecognizer>(); private _rules = new Map<any, RuleSet>();
constructor(@Inject(ROUTER_PRIMARY_COMPONENT) private _rootComponent: Type) {} constructor(@Inject(ROUTER_PRIMARY_COMPONENT) private _rootComponent: Type) {}
@ -95,14 +103,14 @@ export class RouteRegistry {
assertComponentExists(config.component, config.path); assertComponentExists(config.component, config.path);
} }
var recognizer: ComponentRecognizer = this._rules.get(parentComponent); var rules = this._rules.get(parentComponent);
if (isBlank(recognizer)) { if (isBlank(rules)) {
recognizer = new ComponentRecognizer(); rules = new RuleSet();
this._rules.set(parentComponent, recognizer); this._rules.set(parentComponent, rules);
} }
var terminal = recognizer.config(config); var terminal = rules.config(config);
if (config instanceof Route) { if (config instanceof Route) {
if (terminal) { if (terminal) {
@ -159,15 +167,14 @@ export class RouteRegistry {
var parentComponent = isPresent(parentInstruction) ? parentInstruction.component.componentType : var parentComponent = isPresent(parentInstruction) ? parentInstruction.component.componentType :
this._rootComponent; this._rootComponent;
var componentRecognizer = this._rules.get(parentComponent); var rules = this._rules.get(parentComponent);
if (isBlank(componentRecognizer)) { if (isBlank(rules)) {
return _resolveToNull; return _resolveToNull;
} }
// Matches some beginning part of the given URL // Matches some beginning part of the given URL
var possibleMatches: Promise<RouteMatch>[] = var possibleMatches: Promise<RouteMatch>[] =
_aux ? componentRecognizer.recognizeAuxiliary(parsedUrl) : _aux ? rules.recognizeAuxiliary(parsedUrl) : rules.recognize(parsedUrl);
componentRecognizer.recognize(parsedUrl);
var matchPromises: Promise<Instruction>[] = possibleMatches.map( var matchPromises: Promise<Instruction>[] = possibleMatches.map(
(candidate: Promise<RouteMatch>) => candidate.then((candidate: RouteMatch) => { (candidate: Promise<RouteMatch>) => candidate.then((candidate: RouteMatch) => {
@ -184,9 +191,9 @@ export class RouteRegistry {
return instruction; return instruction;
} }
var newAncestorComponents = ancestorInstructions.concat([instruction]); var newAncestorInstructions = ancestorInstructions.concat([instruction]);
return this._recognize(candidate.remaining, newAncestorComponents) return this._recognize(candidate.remaining, newAncestorInstructions)
.then((childInstruction) => { .then((childInstruction) => {
if (isBlank(childInstruction)) { if (isBlank(childInstruction)) {
return null; return null;
@ -359,14 +366,14 @@ export class RouteRegistry {
componentInstruction = prevInstruction.component; componentInstruction = prevInstruction.component;
} }
var componentRecognizer = this._rules.get(parentComponentType); var rules = this._rules.get(parentComponentType);
if (isBlank(componentRecognizer)) { if (isBlank(rules)) {
throw new BaseException( throw new BaseException(
`Component "${getTypeNameForDebugging(parentComponentType)}" has no route config.`); `Component "${getTypeNameForDebugging(parentComponentType)}" has no route config.`);
} }
let linkParamIndex = 0; let linkParamIndex = 0;
let routeParams = {}; let routeParams: {[key: string]: any} = {};
// first, recognize the primary route if one is provided // first, recognize the primary route if one is provided
if (linkParamIndex < linkParams.length && isString(linkParams[linkParamIndex])) { if (linkParamIndex < linkParams.length && isString(linkParams[linkParamIndex])) {
@ -382,8 +389,7 @@ export class RouteRegistry {
linkParamIndex += 1; linkParamIndex += 1;
} }
} }
var routeRecognizer = var routeRecognizer = (_aux ? rules.auxRulesByName : rules.rulesByName).get(routeName);
(_aux ? componentRecognizer.auxNames : componentRecognizer.names).get(routeName);
if (isBlank(routeRecognizer)) { if (isBlank(routeRecognizer)) {
throw new BaseException( throw new BaseException(
@ -394,17 +400,17 @@ export class RouteRegistry {
// we'll figure out the rest of the route when we resolve the instruction and // we'll figure out the rest of the route when we resolve the instruction and
// perform a navigation // perform a navigation
if (isBlank(routeRecognizer.handler.componentType)) { if (isBlank(routeRecognizer.handler.componentType)) {
var compInstruction = routeRecognizer.generateComponentPathValues(routeParams); var generatedUrl = routeRecognizer.generateComponentPathValues(routeParams);
return new UnresolvedInstruction(() => { return new UnresolvedInstruction(() => {
return routeRecognizer.handler.resolveComponentType().then((_) => { return routeRecognizer.handler.resolveComponentType().then((_) => {
return this._generate(linkParams, ancestorInstructions, prevInstruction, _aux, return this._generate(linkParams, ancestorInstructions, prevInstruction, _aux,
_originalLink); _originalLink);
}); });
}, compInstruction['urlPath'], compInstruction['urlParams']); }, generatedUrl.urlPath, convertUrlParamsToArray(generatedUrl.urlParams));
} }
componentInstruction = _aux ? componentRecognizer.generateAuxiliary(routeName, routeParams) : componentInstruction = _aux ? rules.generateAuxiliary(routeName, routeParams) :
componentRecognizer.generate(routeName, routeParams); rules.generate(routeName, routeParams);
} }
// Next, recognize auxiliary instructions. // Next, recognize auxiliary instructions.
@ -442,11 +448,11 @@ export class RouteRegistry {
} }
public hasRoute(name: string, parentComponent: any): boolean { public hasRoute(name: string, parentComponent: any): boolean {
var componentRecognizer: ComponentRecognizer = this._rules.get(parentComponent); var rules = this._rules.get(parentComponent);
if (isBlank(componentRecognizer)) { if (isBlank(rules)) {
return false; return false;
} }
return componentRecognizer.hasRoute(name); return rules.hasRoute(name);
} }
public generateDefault(componentCursor: Type): Instruction { public generateDefault(componentCursor: Type): Instruction {
@ -454,22 +460,22 @@ export class RouteRegistry {
return null; return null;
} }
var componentRecognizer = this._rules.get(componentCursor); var rules = this._rules.get(componentCursor);
if (isBlank(componentRecognizer) || isBlank(componentRecognizer.defaultRoute)) { if (isBlank(rules) || isBlank(rules.defaultRule)) {
return null; return null;
} }
var defaultChild = null; var defaultChild = null;
if (isPresent(componentRecognizer.defaultRoute.handler.componentType)) { if (isPresent(rules.defaultRule.handler.componentType)) {
var componentInstruction = componentRecognizer.defaultRoute.generate({}); var componentInstruction = rules.defaultRule.generate({});
if (!componentRecognizer.defaultRoute.terminal) { if (!rules.defaultRule.terminal) {
defaultChild = this.generateDefault(componentRecognizer.defaultRoute.handler.componentType); defaultChild = this.generateDefault(rules.defaultRule.handler.componentType);
} }
return new DefaultInstruction(componentInstruction, defaultChild); return new DefaultInstruction(componentInstruction, defaultChild);
} }
return new UnresolvedInstruction(() => { return new UnresolvedInstruction(() => {
return componentRecognizer.defaultRoute.handler.resolveComponentType().then( return rules.defaultRule.handler.resolveComponentType().then(
(_) => this.generateDefault(componentCursor)); (_) => this.generateDefault(componentCursor));
}); });
} }
@ -479,17 +485,20 @@ export class RouteRegistry {
* Given: ['/a/b', {c: 2}] * Given: ['/a/b', {c: 2}]
* Returns: ['', 'a', 'b', {c: 2}] * Returns: ['', 'a', 'b', {c: 2}]
*/ */
function splitAndFlattenLinkParams(linkParams: any[]): any[] { function splitAndFlattenLinkParams(linkParams: any[]) {
return linkParams.reduce((accumulation: any[], item) => { var accumulation = [];
linkParams.forEach(function(item: any) {
if (isString(item)) { if (isString(item)) {
let strItem: string = item; var strItem: string = <string>item;
return accumulation.concat(strItem.split('/')); accumulation = accumulation.concat(strItem.split('/'));
} else {
accumulation.push(item);
} }
accumulation.push(item); });
return accumulation; return accumulation;
}, []);
} }
/* /*
* Given a list of instructions, returns the most specific instruction * Given a list of instructions, returns the most specific instruction
*/ */

View File

@ -9,10 +9,10 @@ import {
ComponentInstruction, ComponentInstruction,
Instruction, Instruction,
} from './instruction'; } from './instruction';
import {RouterOutlet} from './router_outlet'; import {RouterOutlet} from './directives/router_outlet';
import {Location} from './location'; import {Location} from './location/location';
import {getCanActivateHook} from './route_lifecycle_reflector'; import {getCanActivateHook} from './lifecycle/route_lifecycle_reflector';
import {RouteDefinition} from './route_config_impl'; import {RouteDefinition} from './route_config/route_config_impl';
let _resolveToTrue = PromiseWrapper.resolve(true); let _resolveToTrue = PromiseWrapper.resolve(true);
let _resolveToFalse = PromiseWrapper.resolve(false); let _resolveToFalse = PromiseWrapper.resolve(false);

View File

@ -2,8 +2,8 @@
import {ROUTER_PROVIDERS_COMMON} from 'angular2/router'; import {ROUTER_PROVIDERS_COMMON} from 'angular2/router';
import {Provider} from 'angular2/core'; import {Provider} from 'angular2/core';
import {CONST_EXPR} from 'angular2/src/facade/lang'; import {CONST_EXPR} from 'angular2/src/facade/lang';
import {BrowserPlatformLocation} from './browser_platform_location'; import {BrowserPlatformLocation} from './location/browser_platform_location';
import {PlatformLocation} from './platform_location'; import {PlatformLocation} from './location/platform_location';
/** /**
* A list of {@link Provider}s. To use the router, you must add this to your application. * A list of {@link Provider}s. To use the router, you must add this to your application.

View File

@ -1,8 +1,8 @@
import {LocationStrategy} from 'angular2/src/router/location_strategy'; import {LocationStrategy} from 'angular2/src/router/location/location_strategy';
import {PathLocationStrategy} from 'angular2/src/router/path_location_strategy'; import {PathLocationStrategy} from 'angular2/src/router/location/path_location_strategy';
import {Router, RootRouter} from 'angular2/src/router/router'; import {Router, RootRouter} from 'angular2/src/router/router';
import {RouteRegistry, ROUTER_PRIMARY_COMPONENT} from 'angular2/src/router/route_registry'; import {RouteRegistry, ROUTER_PRIMARY_COMPONENT} from 'angular2/src/router/route_registry';
import {Location} from 'angular2/src/router/location'; import {Location} from 'angular2/src/router/location/location';
import {CONST_EXPR, Type} from 'angular2/src/facade/lang'; import {CONST_EXPR, Type} from 'angular2/src/facade/lang';
import {ApplicationRef, OpaqueToken, Provider} from 'angular2/core'; import {ApplicationRef, OpaqueToken, Provider} from 'angular2/core';
import {BaseException} from 'angular2/src/facade/exceptions'; import {BaseException} from 'angular2/src/facade/exceptions';

View File

@ -1,7 +1,7 @@
import {isPresent, Type} from 'angular2/src/facade/lang'; import {isPresent, Type} from 'angular2/src/facade/lang';
import {RouteHandler} from './route_handler'; import {RouteHandler} from './route_handler';
import {RouteData, BLANK_ROUTE_DATA} from './instruction'; import {RouteData, BLANK_ROUTE_DATA} from '../../instruction';
export class AsyncRouteHandler implements RouteHandler { export class AsyncRouteHandler implements RouteHandler {

View File

@ -1,5 +1,5 @@
import {Type} from 'angular2/src/facade/lang'; import {Type} from 'angular2/src/facade/lang';
import {RouteData} from './instruction'; import {RouteData} from '../../instruction';
export interface RouteHandler { export interface RouteHandler {
componentType: Type; componentType: Type;

View File

@ -2,7 +2,7 @@ import {PromiseWrapper} from 'angular2/src/facade/async';
import {isPresent, Type} from 'angular2/src/facade/lang'; import {isPresent, Type} from 'angular2/src/facade/lang';
import {RouteHandler} from './route_handler'; import {RouteHandler} from './route_handler';
import {RouteData, BLANK_ROUTE_DATA} from './instruction'; import {RouteData, BLANK_ROUTE_DATA} from '../../instruction';
export class SyncRouteHandler implements RouteHandler { export class SyncRouteHandler implements RouteHandler {

View File

@ -0,0 +1,271 @@
import {RegExpWrapper, StringWrapper, isPresent, isBlank} from 'angular2/src/facade/lang';
import {BaseException} from 'angular2/src/facade/exceptions';
import {StringMapWrapper} from 'angular2/src/facade/collection';
import {TouchMap, normalizeString} from '../../utils';
import {Url, RootUrl, convertUrlParamsToArray} from '../../url_parser';
import {RoutePath, GeneratedUrl, MatchedUrl} from './route_path';
/**
* `ParamRoutePath`s are made up of `PathSegment`s, each of which can
* match a segment of a URL. Different kind of `PathSegment`s match
* URL segments in different ways...
*/
interface PathSegment {
name: string;
generate(params: TouchMap): string;
match(path: string): boolean;
specificity: string;
hash: string;
}
/**
* Identified by a `...` URL segment. This indicates that the
* Route will continue to be matched by child `Router`s.
*/
class ContinuationPathSegment implements PathSegment {
name: string = '';
specificity = '';
hash = '...';
generate(params: TouchMap): string { return ''; }
match(path: string): boolean { return true; }
}
/**
* Identified by a string not starting with a `:` or `*`.
* Only matches the URL segments that equal the segment path
*/
class StaticPathSegment implements PathSegment {
name: string = '';
specificity = '2';
hash: string;
constructor(public path: string) { this.hash = path; }
match(path: string): boolean { return path == this.path; }
generate(params: TouchMap): string { return this.path; }
}
/**
* Identified by a string starting with `:`. Indicates a segment
* that can contain a value that will be extracted and provided to
* a matching `Instruction`.
*/
class DynamicPathSegment implements PathSegment {
static paramMatcher = /^:([^\/]+)$/g;
specificity = '1';
hash = ':';
constructor(public name: string) {}
match(path: string): boolean { return path.length > 0; }
generate(params: TouchMap): string {
if (!StringMapWrapper.contains(params.map, this.name)) {
throw new BaseException(
`Route generator for '${this.name}' was not included in parameters passed.`);
}
return normalizeString(params.get(this.name));
}
}
/**
* Identified by a string starting with `*` Indicates that all the following
* segments match this route and that the value of these segments should
* be provided to a matching `Instruction`.
*/
class StarPathSegment implements PathSegment {
static wildcardMatcher = /^\*([^\/]+)$/g;
specificity = '0';
hash = '*';
constructor(public name: string) {}
match(path: string): boolean { return true; }
generate(params: TouchMap): string { return normalizeString(params.get(this.name)); }
}
/**
* Parses a URL string using a given matcher DSL, and generates URLs from param maps
*/
export class ParamRoutePath implements RoutePath {
specificity: string;
terminal: boolean = true;
hash: string;
private _segments: PathSegment[];
/**
* Takes a string representing the matcher DSL
*/
constructor(public routePath: string) {
this._assertValidPath(routePath);
this._parsePathString(routePath);
this.specificity = this._calculateSpecificity();
this.hash = this._calculateHash();
var lastSegment = this._segments[this._segments.length - 1];
this.terminal = !(lastSegment instanceof ContinuationPathSegment);
}
matchUrl(url: Url): MatchedUrl {
var nextUrlSegment = url;
var currentUrlSegment: Url;
var positionalParams = {};
var captured: string[] = [];
for (var i = 0; i < this._segments.length; i += 1) {
var pathSegment = this._segments[i];
currentUrlSegment = nextUrlSegment;
if (pathSegment instanceof ContinuationPathSegment) {
break;
}
if (isPresent(currentUrlSegment)) {
// the star segment consumes all of the remaining URL, including matrix params
if (pathSegment instanceof StarPathSegment) {
positionalParams[pathSegment.name] = currentUrlSegment.toString();
captured.push(currentUrlSegment.toString());
nextUrlSegment = null;
break;
}
captured.push(currentUrlSegment.path);
if (pathSegment instanceof DynamicPathSegment) {
positionalParams[pathSegment.name] = currentUrlSegment.path;
} else if (!pathSegment.match(currentUrlSegment.path)) {
return null;
}
nextUrlSegment = currentUrlSegment.child;
} else if (!pathSegment.match('')) {
return null;
}
}
if (this.terminal && isPresent(nextUrlSegment)) {
return null;
}
var urlPath = captured.join('/');
var auxiliary = [];
var urlParams = [];
var allParams = positionalParams;
if (isPresent(currentUrlSegment)) {
// If this is the root component, read query params. Otherwise, read matrix params.
var paramsSegment = url instanceof RootUrl ? url : currentUrlSegment;
if (isPresent(paramsSegment.params)) {
allParams = StringMapWrapper.merge(paramsSegment.params, positionalParams);
urlParams = convertUrlParamsToArray(paramsSegment.params);
} else {
allParams = positionalParams;
}
auxiliary = currentUrlSegment.auxiliary;
}
return new MatchedUrl(urlPath, urlParams, allParams, auxiliary, nextUrlSegment);
}
generateUrl(params: {[key: string]: any}): GeneratedUrl {
var paramTokens = new TouchMap(params);
var path = [];
for (var i = 0; i < this._segments.length; i++) {
let segment = this._segments[i];
if (!(segment instanceof ContinuationPathSegment)) {
path.push(segment.generate(paramTokens));
}
}
var urlPath = path.join('/');
var nonPositionalParams = paramTokens.getUnused();
var urlParams = nonPositionalParams;
return new GeneratedUrl(urlPath, urlParams);
}
toString(): string { return this.routePath; }
private _parsePathString(routePath: string) {
// normalize route as not starting with a "/". Recognition will
// also normalize.
if (routePath.startsWith("/")) {
routePath = routePath.substring(1);
}
var segmentStrings = routePath.split('/');
this._segments = [];
var limit = segmentStrings.length - 1;
for (var i = 0; i <= limit; i++) {
var segment = segmentStrings[i], match;
if (isPresent(match = RegExpWrapper.firstMatch(DynamicPathSegment.paramMatcher, segment))) {
this._segments.push(new DynamicPathSegment(match[1]));
} else if (isPresent(
match = RegExpWrapper.firstMatch(StarPathSegment.wildcardMatcher, segment))) {
this._segments.push(new StarPathSegment(match[1]));
} else if (segment == '...') {
if (i < limit) {
throw new BaseException(
`Unexpected "..." before the end of the path for "${routePath}".`);
}
this._segments.push(new ContinuationPathSegment());
} else {
this._segments.push(new StaticPathSegment(segment));
}
}
}
private _calculateSpecificity(): string {
// The "specificity" of a path is used to determine which route is used when multiple routes
// match
// a URL. Static segments (like "/foo") are the most specific, followed by dynamic segments
// (like
// "/:id"). Star segments add no specificity. Segments at the start of the path are more
// specific
// than proceeding ones.
//
// The code below uses place values to combine the different types of segments into a single
// string that we can sort later. Each static segment is marked as a specificity of "2," each
// dynamic segment is worth "1" specificity, and stars are worth "0" specificity.
var i, length = this._segments.length, specificity;
if (length == 0) {
// a single slash (or "empty segment" is as specific as a static segment
specificity += '2';
} else {
specificity = '';
for (i = 0; i < length; i++) {
specificity += this._segments[i].specificity;
}
}
return specificity;
}
private _calculateHash(): string {
// this function is used to determine whether a route config path like `/foo/:id` collides with
// `/foo/:name`
var i, length = this._segments.length;
var hashParts = [];
for (i = 0; i < length; i++) {
hashParts.push(this._segments[i].hash);
}
return hashParts.join('/');
}
private _assertValidPath(path: string) {
if (StringWrapper.contains(path, '#')) {
throw new BaseException(
`Path "${path}" should not include "#". Use "HashLocationStrategy" instead.`);
}
var illegalCharacter = RegExpWrapper.firstMatch(ParamRoutePath.RESERVED_CHARS, path);
if (isPresent(illegalCharacter)) {
throw new BaseException(
`Path "${path}" contains "${illegalCharacter[0]}" which is not allowed in a route config.`);
}
}
static RESERVED_CHARS = RegExpWrapper.create('//|\\(|\\)|;|\\?|=');
}

View File

@ -0,0 +1,40 @@
import {RegExpWrapper, RegExpMatcherWrapper, isBlank} from 'angular2/src/facade/lang';
import {Url, RootUrl} from '../../url_parser';
import {RoutePath, GeneratedUrl, MatchedUrl} from './route_path';
export interface RegexSerializer { (params: {[key: string]: any}): GeneratedUrl; }
export class RegexRoutePath implements RoutePath {
public hash: string;
public terminal: boolean = true;
public specificity: string = '2';
private _regex: RegExp;
constructor(private _reString: string, private _serializer: RegexSerializer) {
this.hash = this._reString;
this._regex = RegExpWrapper.create(this._reString);
}
matchUrl(url: Url): MatchedUrl {
var urlPath = url.toString();
var params: {[key: string]: string} = {};
var matcher = RegExpWrapper.matcher(this._regex, urlPath);
var match = RegExpMatcherWrapper.next(matcher);
if (isBlank(match)) {
return null;
}
for (let i = 0; i < match.length; i += 1) {
params[i.toString()] = match[i];
}
return new MatchedUrl(urlPath, [], params, [], null);
}
generateUrl(params: {[key: string]: any}): GeneratedUrl { return this._serializer(params); }
toString() { return this._reString; }
}

View File

@ -0,0 +1,20 @@
import {Url} from '../../url_parser';
export class MatchedUrl {
constructor(public urlPath: string, public urlParams: string[],
public allParams: {[key: string]: any}, public auxiliary: Url[], public rest: Url) {}
}
export class GeneratedUrl {
constructor(public urlPath: string, public urlParams: {[key: string]: any}) {}
}
export interface RoutePath {
specificity: string;
terminal: boolean;
hash: string;
matchUrl(url: Url): MatchedUrl;
generateUrl(params: {[key: string]: any}): GeneratedUrl;
toString(): string;
}

View File

@ -0,0 +1,191 @@
import {isBlank, isPresent, isFunction} from 'angular2/src/facade/lang';
import {BaseException, WrappedException} from 'angular2/src/facade/exceptions';
import {Map, MapWrapper, ListWrapper, StringMapWrapper} from 'angular2/src/facade/collection';
import {PromiseWrapper} from 'angular2/src/facade/async';
import {AbstractRule, RouteRule, RedirectRule, RouteMatch, PathMatch} from './rules';
import {
Route,
AsyncRoute,
AuxRoute,
Redirect,
RouteDefinition
} from '../route_config/route_config_impl';
import {AsyncRouteHandler} from './route_handlers/async_route_handler';
import {SyncRouteHandler} from './route_handlers/sync_route_handler';
import {RoutePath} from './route_paths/route_path';
import {ParamRoutePath} from './route_paths/param_route_path';
import {RegexRoutePath} from './route_paths/regex_route_path';
import {Url} from '../url_parser';
import {ComponentInstruction} from '../instruction';
/**
* A `RuleSet` is responsible for recognizing routes for a particular component.
* It is consumed by `RouteRegistry`, which knows how to recognize an entire hierarchy of
* components.
*/
export class RuleSet {
rulesByName = new Map<string, RouteRule>();
// map from name to rule
auxRulesByName = new Map<string, RouteRule>();
// map from starting path to rule
auxRulesByPath = new Map<string, RouteRule>();
// TODO: optimize this into a trie
rules: AbstractRule[] = [];
// the rule to use automatically when recognizing or generating from this rule set
defaultRule: RouteRule = null;
/**
* Configure additional rules in this rule set from a route definition
* @returns {boolean} true if the config is terminal
*/
config(config: RouteDefinition): boolean {
let handler;
if (isPresent(config.name) && config.name[0].toUpperCase() != config.name[0]) {
let suggestedName = config.name[0].toUpperCase() + config.name.substring(1);
throw new BaseException(
`Route "${config.path}" with name "${config.name}" does not begin with an uppercase letter. Route names should be CamelCase like "${suggestedName}".`);
}
if (config instanceof AuxRoute) {
handler = new SyncRouteHandler(config.component, config.data);
let routePath = this._getRoutePath(config);
let auxRule = new RouteRule(routePath, handler);
this.auxRulesByPath.set(routePath.toString(), auxRule);
if (isPresent(config.name)) {
this.auxRulesByName.set(config.name, auxRule);
}
return auxRule.terminal;
}
let useAsDefault = false;
if (config instanceof Redirect) {
let routePath = this._getRoutePath(config);
let redirector = new RedirectRule(routePath, config.redirectTo);
this._assertNoHashCollision(redirector.hash, config.path);
this.rules.push(redirector);
return true;
}
if (config instanceof Route) {
handler = new SyncRouteHandler(config.component, config.data);
useAsDefault = isPresent(config.useAsDefault) && config.useAsDefault;
} else if (config instanceof AsyncRoute) {
handler = new AsyncRouteHandler(config.loader, config.data);
useAsDefault = isPresent(config.useAsDefault) && config.useAsDefault;
}
let routePath = this._getRoutePath(config);
let newRule = new RouteRule(routePath, handler);
this._assertNoHashCollision(newRule.hash, config.path);
if (useAsDefault) {
if (isPresent(this.defaultRule)) {
throw new BaseException(`Only one route can be default`);
}
this.defaultRule = newRule;
}
this.rules.push(newRule);
if (isPresent(config.name)) {
this.rulesByName.set(config.name, newRule);
}
return newRule.terminal;
}
/**
* Given a URL, returns a list of `RouteMatch`es, which are partial recognitions for some route.
*/
recognize(urlParse: Url): Promise<RouteMatch>[] {
var solutions = [];
this.rules.forEach((routeRecognizer: AbstractRule) => {
var pathMatch = routeRecognizer.recognize(urlParse);
if (isPresent(pathMatch)) {
solutions.push(pathMatch);
}
});
// handle cases where we are routing just to an aux route
if (solutions.length == 0 && isPresent(urlParse) && urlParse.auxiliary.length > 0) {
return [PromiseWrapper.resolve(new PathMatch(null, null, urlParse.auxiliary))];
}
return solutions;
}
recognizeAuxiliary(urlParse: Url): Promise<RouteMatch>[] {
var routeRecognizer: RouteRule = this.auxRulesByPath.get(urlParse.path);
if (isPresent(routeRecognizer)) {
return [routeRecognizer.recognize(urlParse)];
}
return [PromiseWrapper.resolve(null)];
}
hasRoute(name: string): boolean { return this.rulesByName.has(name); }
componentLoaded(name: string): boolean {
return this.hasRoute(name) && isPresent(this.rulesByName.get(name).handler.componentType);
}
loadComponent(name: string): Promise<any> {
return this.rulesByName.get(name).handler.resolveComponentType();
}
generate(name: string, params: any): ComponentInstruction {
var rule: RouteRule = this.rulesByName.get(name);
if (isBlank(rule)) {
return null;
}
return rule.generate(params);
}
generateAuxiliary(name: string, params: any): ComponentInstruction {
var rule: RouteRule = this.auxRulesByName.get(name);
if (isBlank(rule)) {
return null;
}
return rule.generate(params);
}
private _assertNoHashCollision(hash: string, path) {
this.rules.forEach((rule) => {
if (hash == rule.hash) {
throw new BaseException(
`Configuration '${path}' conflicts with existing route '${rule.path}'`);
}
});
}
private _getRoutePath(config: RouteDefinition): RoutePath {
if (isPresent(config.regex)) {
if (isFunction(config.serializer)) {
return new RegexRoutePath(config.regex, config.serializer);
} else {
throw new BaseException(
`Route provides a regex property, '${config.regex}', but no serializer property`);
}
}
if (isPresent(config.path)) {
// Auxiliary routes do not have a slash at the start
let path = (config instanceof AuxRoute && config.path.startsWith('/')) ?
config.path.substring(1) :
config.path;
return new ParamRoutePath(path);
}
throw new BaseException('Route must provide either a path or regex property');
}
}

View File

@ -3,22 +3,16 @@ import {BaseException} from 'angular2/src/facade/exceptions';
import {PromiseWrapper} from 'angular2/src/facade/promise'; import {PromiseWrapper} from 'angular2/src/facade/promise';
import {Map} from 'angular2/src/facade/collection'; import {Map} from 'angular2/src/facade/collection';
import {RouteHandler} from './route_handler'; import {RouteHandler} from './route_handlers/route_handler';
import {Url} from './url_parser'; import {Url, convertUrlParamsToArray} from '../url_parser';
import {ComponentInstruction} from './instruction'; import {ComponentInstruction} from '../instruction';
import {PathRecognizer} from './path_recognizer'; import {RoutePath} from './route_paths/route_path';
import {GeneratedUrl} from './route_paths/route_path';
// RouteMatch objects hold information about a match between a rule and a URL
export abstract class RouteMatch {} export abstract class RouteMatch {}
export interface AbstractRecognizer {
hash: string;
path: string;
recognize(beginningSegment: Url): Promise<RouteMatch>;
generate(params: {[key: string]: any}): ComponentInstruction;
}
export class PathMatch extends RouteMatch { export class PathMatch extends RouteMatch {
constructor(public instruction: ComponentInstruction, public remaining: Url, constructor(public instruction: ComponentInstruction, public remaining: Url,
public remainingAux: Url[]) { public remainingAux: Url[]) {
@ -26,26 +20,34 @@ export class PathMatch extends RouteMatch {
} }
} }
export class RedirectMatch extends RouteMatch { export class RedirectMatch extends RouteMatch {
constructor(public redirectTo: any[], public specificity) { super(); } constructor(public redirectTo: any[], public specificity) { super(); }
} }
export class RedirectRecognizer implements AbstractRecognizer { // Rules are responsible for recognizing URL segments and generating instructions
private _pathRecognizer: PathRecognizer; export interface AbstractRule {
hash: string;
path: string;
recognize(beginningSegment: Url): Promise<RouteMatch>;
generate(params: {[key: string]: any}): ComponentInstruction;
}
export class RedirectRule implements AbstractRule {
public hash: string; public hash: string;
constructor(public path: string, public redirectTo: any[]) { constructor(private _pathRecognizer: RoutePath, public redirectTo: any[]) {
this._pathRecognizer = new PathRecognizer(path);
this.hash = this._pathRecognizer.hash; this.hash = this._pathRecognizer.hash;
} }
get path() { return this._pathRecognizer.toString(); }
set path(val) { throw new BaseException('you cannot set the path of a RedirectRule directly'); }
/** /**
* Returns `null` or a `ParsedUrl` representing the new path to match * Returns `null` or a `ParsedUrl` representing the new path to match
*/ */
recognize(beginningSegment: Url): Promise<RouteMatch> { recognize(beginningSegment: Url): Promise<RouteMatch> {
var match = null; var match = null;
if (isPresent(this._pathRecognizer.recognize(beginningSegment))) { if (isPresent(this._pathRecognizer.matchUrl(beginningSegment))) {
match = new RedirectMatch(this.redirectTo, this._pathRecognizer.specificity); match = new RedirectMatch(this.redirectTo, this._pathRecognizer.specificity);
} }
return PromiseWrapper.resolve(match); return PromiseWrapper.resolve(match);
@ -58,45 +60,45 @@ export class RedirectRecognizer implements AbstractRecognizer {
// represents something like '/foo/:bar' // represents something like '/foo/:bar'
export class RouteRecognizer implements AbstractRecognizer { export class RouteRule implements AbstractRule {
specificity: string; specificity: string;
terminal: boolean = true; terminal: boolean;
hash: string; hash: string;
private _cache: Map<string, ComponentInstruction> = new Map<string, ComponentInstruction>(); private _cache: Map<string, ComponentInstruction> = new Map<string, ComponentInstruction>();
private _pathRecognizer: PathRecognizer;
// TODO: cache component instruction instances by params and by ParsedUrl instance // TODO: cache component instruction instances by params and by ParsedUrl instance
constructor(public path: string, public handler: RouteHandler) { constructor(private _routePath: RoutePath, public handler: RouteHandler) {
this._pathRecognizer = new PathRecognizer(path); this.specificity = this._routePath.specificity;
this.specificity = this._pathRecognizer.specificity; this.hash = this._routePath.hash;
this.hash = this._pathRecognizer.hash; this.terminal = this._routePath.terminal;
this.terminal = this._pathRecognizer.terminal;
} }
get path() { return this._routePath.toString(); }
set path(val) { throw new BaseException('you cannot set the path of a RouteRule directly'); }
recognize(beginningSegment: Url): Promise<RouteMatch> { recognize(beginningSegment: Url): Promise<RouteMatch> {
var res = this._pathRecognizer.recognize(beginningSegment); var res = this._routePath.matchUrl(beginningSegment);
if (isBlank(res)) { if (isBlank(res)) {
return null; return null;
} }
return this.handler.resolveComponentType().then((_) => { return this.handler.resolveComponentType().then((_) => {
var componentInstruction = var componentInstruction = this._getInstruction(res.urlPath, res.urlParams, res.allParams);
this._getInstruction(res['urlPath'], res['urlParams'], res['allParams']); return new PathMatch(componentInstruction, res.rest, res.auxiliary);
return new PathMatch(componentInstruction, res['nextSegment'], res['auxiliary']);
}); });
} }
generate(params: {[key: string]: any}): ComponentInstruction { generate(params: {[key: string]: any}): ComponentInstruction {
var generated = this._pathRecognizer.generate(params); var generated = this._routePath.generateUrl(params);
var urlPath = generated['urlPath']; var urlPath = generated.urlPath;
var urlParams = generated['urlParams']; var urlParams = generated.urlParams;
return this._getInstruction(urlPath, urlParams, params); return this._getInstruction(urlPath, convertUrlParamsToArray(urlParams), params);
} }
generateComponentPathValues(params: {[key: string]: any}): {[key: string]: any} { generateComponentPathValues(params: {[key: string]: any}): GeneratedUrl {
return this._pathRecognizer.generate(params); return this._routePath.generateUrl(params);
} }
private _getInstruction(urlPath: string, urlParams: string[], private _getInstruction(urlPath: string, urlParams: string[],
@ -104,8 +106,7 @@ export class RouteRecognizer implements AbstractRecognizer {
if (isBlank(this.handler.componentType)) { if (isBlank(this.handler.componentType)) {
throw new BaseException(`Tried to get instruction before the type was loaded.`); throw new BaseException(`Tried to get instruction before the type was loaded.`);
} }
var hashKey = urlPath + '?' + urlParams.join('&');
var hashKey = urlPath + '?' + urlParams.join('?');
if (this._cache.has(hashKey)) { if (this._cache.has(hashKey)) {
return this._cache.get(hashKey); return this._cache.get(hashKey);
} }

View File

@ -2,13 +2,28 @@ import {StringMapWrapper} from 'angular2/src/facade/collection';
import {isPresent, isBlank, RegExpWrapper, CONST_EXPR} from 'angular2/src/facade/lang'; import {isPresent, isBlank, RegExpWrapper, CONST_EXPR} from 'angular2/src/facade/lang';
import {BaseException, WrappedException} from 'angular2/src/facade/exceptions'; import {BaseException, WrappedException} from 'angular2/src/facade/exceptions';
export function convertUrlParamsToArray(urlParams: {[key: string]: any}): string[] {
var paramsArray = [];
if (isBlank(urlParams)) {
return [];
}
StringMapWrapper.forEach(
urlParams, (value, key) => { paramsArray.push((value === true) ? key : key + '=' + value); });
return paramsArray;
}
// Convert an object of url parameters into a string that can be used in an URL
export function serializeParams(urlParams: {[key: string]: any}, joiner = '&'): string {
return convertUrlParamsToArray(urlParams).join(joiner);
}
/** /**
* This class represents a parsed URL * This class represents a parsed URL
*/ */
export class Url { export class Url {
constructor(public path: string, public child: Url = null, constructor(public path: string, public child: Url = null,
public auxiliary: Url[] = CONST_EXPR([]), public auxiliary: Url[] = CONST_EXPR([]),
public params: {[key: string]: any} = null) {} public params: {[key: string]: any} = CONST_EXPR({})) {}
toString(): string { toString(): string {
return this.path + this._matrixParamsToString() + this._auxToString() + this._childString(); return this.path + this._matrixParamsToString() + this._auxToString() + this._childString();
@ -24,11 +39,11 @@ export class Url {
} }
private _matrixParamsToString(): string { private _matrixParamsToString(): string {
if (isBlank(this.params)) { var paramString = serializeParams(this.params, ';');
return ''; if (paramString.length > 0) {
return ';' + paramString;
} }
return '';
return ';' + serializeParams(this.params).join(';');
} }
/** @internal */ /** @internal */
@ -52,7 +67,7 @@ export class RootUrl extends Url {
return ''; return '';
} }
return '?' + serializeParams(this.params).join('&'); return '?' + serializeParams(this.params);
} }
} }
@ -91,7 +106,7 @@ export class UrlParser {
} }
// segment + (aux segments) + (query params) // segment + (aux segments) + (query params)
parseRoot(): Url { parseRoot(): RootUrl {
if (this.peekStartsWith('/')) { if (this.peekStartsWith('/')) {
this.capture('/'); this.capture('/');
} }
@ -200,18 +215,4 @@ export class UrlParser {
} }
} }
export var parser = new UrlParser(); export var parser = new UrlParser();
export function serializeParams(paramMap: {[key: string]: any}): string[] {
var params = [];
if (isPresent(paramMap)) {
StringMapWrapper.forEach(paramMap, (value, key) => {
if (value === true) {
params.push(key);
} else {
params.push(key + '=' + value);
}
});
}
return params;
}

View File

@ -0,0 +1,37 @@
import {isPresent, isBlank} from 'angular2/src/facade/lang';
import {StringMapWrapper} from 'angular2/src/facade/collection';
export class TouchMap {
map: {[key: string]: string} = {};
keys: {[key: string]: boolean} = {};
constructor(map: {[key: string]: any}) {
if (isPresent(map)) {
StringMapWrapper.forEach(map, (value, key) => {
this.map[key] = isPresent(value) ? value.toString() : null;
this.keys[key] = true;
});
}
}
get(key: string): string {
StringMapWrapper.delete(this.keys, key);
return this.map[key];
}
getUnused(): {[key: string]: any} {
var unused: {[key: string]: any} = {};
var keys = StringMapWrapper.keys(this.keys);
keys.forEach(key => unused[key] = StringMapWrapper.get(this.map, key));
return unused;
}
}
export function normalizeString(obj: any): string {
if (isBlank(obj)) {
return null;
} else {
return obj.toString();
}
}

View File

@ -1,4 +1,4 @@
import {BrowserPlatformLocation} from 'angular2/src/router/browser_platform_location'; import {BrowserPlatformLocation} from 'angular2/src/router/location/browser_platform_location';
import {Injectable} from 'angular2/src/core/di'; import {Injectable} from 'angular2/src/core/di';
import {ROUTER_CHANNEL} from 'angular2/src/web_workers/shared/messaging_api'; import {ROUTER_CHANNEL} from 'angular2/src/web_workers/shared/messaging_api';
import { import {
@ -10,7 +10,7 @@ import {bind} from './bind';
import {LocationType} from 'angular2/src/web_workers/shared/serialized_types'; import {LocationType} from 'angular2/src/web_workers/shared/serialized_types';
import {MessageBus} from 'angular2/src/web_workers/shared/message_bus'; import {MessageBus} from 'angular2/src/web_workers/shared/message_bus';
import {EventEmitter, ObservableWrapper, PromiseWrapper} from 'angular2/src/facade/async'; import {EventEmitter, ObservableWrapper, PromiseWrapper} from 'angular2/src/facade/async';
import {UrlChangeListener} from 'angular2/src/router/platform_location'; import {UrlChangeListener} from 'angular2/src/router/location/platform_location';
@Injectable() @Injectable()
export class MessageBasedPlatformLocation { export class MessageBasedPlatformLocation {

View File

@ -1,6 +1,6 @@
import {MessageBasedPlatformLocation} from './platform_location'; import {MessageBasedPlatformLocation} from './platform_location';
import {CONST_EXPR} from 'angular2/src/facade/lang'; import {CONST_EXPR} from 'angular2/src/facade/lang';
import {BrowserPlatformLocation} from 'angular2/src/router/browser_platform_location'; import {BrowserPlatformLocation} from 'angular2/src/router/location/browser_platform_location';
import {APP_INITIALIZER, Provider, Injector, NgZone} from 'angular2/core'; import {APP_INITIALIZER, Provider, Injector, NgZone} from 'angular2/core';
export const WORKER_RENDER_ROUTER = CONST_EXPR([ export const WORKER_RENDER_ROUTER = CONST_EXPR([

View File

@ -3,7 +3,7 @@ import {
PlatformLocation, PlatformLocation,
UrlChangeEvent, UrlChangeEvent,
UrlChangeListener UrlChangeListener
} from 'angular2/src/router/platform_location'; } from 'angular2/src/router/location/platform_location';
import { import {
FnArg, FnArg,
UiArguments, UiArguments,

View File

@ -1,5 +1,5 @@
import {ApplicationRef, Provider, NgZone, APP_INITIALIZER} from 'angular2/core'; import {ApplicationRef, Provider, NgZone, APP_INITIALIZER} from 'angular2/core';
import {PlatformLocation} from 'angular2/src/router/platform_location'; import {PlatformLocation} from 'angular2/src/router/location/platform_location';
import {WebWorkerPlatformLocation} from './platform_location'; import {WebWorkerPlatformLocation} from './platform_location';
import {ROUTER_PROVIDERS_COMMON} from 'angular2/src/router/router_providers_common'; import {ROUTER_PROVIDERS_COMMON} from 'angular2/src/router/router_providers_common';

View File

@ -14,7 +14,7 @@ import {
TestComponentBuilder TestComponentBuilder
} from 'angular2/testing_internal'; } from 'angular2/testing_internal';
import {SpyRouter, SpyLocation} from './spies'; import {SpyRouter, SpyLocation} from '../spies';
import {provide, Component, View} from 'angular2/core'; import {provide, Component, View} from 'angular2/core';
import {By} from 'angular2/platform/common_dom'; import {By} from 'angular2/platform/common_dom';

View File

@ -15,8 +15,8 @@ import {
import {Injector, provide} from 'angular2/core'; import {Injector, provide} from 'angular2/core';
import {CONST_EXPR} from 'angular2/src/facade/lang'; import {CONST_EXPR} from 'angular2/src/facade/lang';
import {parseRouterLinkExpression} from 'angular2/src/router/router_link_transform'; import {parseRouterLinkExpression} from 'angular2/src/router/directives/router_link_transform';
import {Unparser} from '../core/change_detection/parser/unparser'; import {Unparser} from '../../core/change_detection/parser/unparser';
import {Parser} from 'angular2/src/core/change_detection/parser/parser'; import {Parser} from 'angular2/src/core/change_detection/parser/parser';
export function main() { export function main() {

View File

@ -20,7 +20,12 @@ import {DOM} from 'angular2/src/platform/dom/dom_adapter';
import {Console} from 'angular2/src/core/console'; import {Console} from 'angular2/src/core/console';
import {provide, ViewChild, AfterViewInit} from 'angular2/core'; import {provide, ViewChild, AfterViewInit} from 'angular2/core';
import {DOCUMENT} from 'angular2/src/platform/dom/dom_tokens'; import {DOCUMENT} from 'angular2/src/platform/dom/dom_tokens';
import {RouteConfig, Route, Redirect, AuxRoute} from 'angular2/src/router/route_config_decorator'; import {
RouteConfig,
Route,
Redirect,
AuxRoute
} from 'angular2/src/router/route_config/route_config_decorator';
import {PromiseWrapper} from 'angular2/src/facade/async'; import {PromiseWrapper} from 'angular2/src/facade/async';
import {BaseException, WrappedException} from 'angular2/src/facade/exceptions'; import {BaseException, WrappedException} from 'angular2/src/facade/exceptions';
import { import {

View File

@ -19,7 +19,12 @@ import {By} from 'angular2/platform/common_dom';
import {provide, Component, Injector, Inject} from 'angular2/core'; import {provide, Component, Injector, Inject} from 'angular2/core';
import {Router, ROUTER_DIRECTIVES, RouteParams, RouteData, Location} from 'angular2/router'; import {Router, ROUTER_DIRECTIVES, RouteParams, RouteData, Location} from 'angular2/router';
import {RouteConfig, Route, AuxRoute, Redirect} from 'angular2/src/router/route_config_decorator'; import {
RouteConfig,
Route,
AuxRoute,
Redirect
} from 'angular2/src/router/route_config/route_config_decorator';
import {specs, compile, TEST_ROUTER_PROVIDERS, clickOnElement, getHref} from '../util'; import {specs, compile, TEST_ROUTER_PROVIDERS, clickOnElement, getHref} from '../util';
import {BaseException} from 'angular2/src/facade/exceptions'; import {BaseException} from 'angular2/src/facade/exceptions';

View File

@ -31,7 +31,7 @@ import {
AuxRoute, AuxRoute,
AsyncRoute, AsyncRoute,
Redirect Redirect
} from 'angular2/src/router/route_config_decorator'; } from 'angular2/src/router/route_config/route_config_decorator';
import { import {
OnActivate, OnActivate,
@ -40,7 +40,7 @@ import {
CanDeactivate, CanDeactivate,
CanReuse CanReuse
} from 'angular2/src/router/interfaces'; } from 'angular2/src/router/interfaces';
import {CanActivate} from 'angular2/src/router/lifecycle_annotations'; import {CanActivate} from 'angular2/src/router/lifecycle/lifecycle_annotations';
import {ComponentInstruction} from 'angular2/src/router/instruction'; import {ComponentInstruction} from 'angular2/src/router/instruction';

View File

@ -25,7 +25,7 @@ import {
AuxRoute, AuxRoute,
AsyncRoute, AsyncRoute,
Redirect Redirect
} from 'angular2/src/router/route_config_decorator'; } from 'angular2/src/router/route_config/route_config_decorator';
import {TEST_ROUTER_PROVIDERS, RootCmp, compile} from './util'; import {TEST_ROUTER_PROVIDERS, RootCmp, compile} from './util';

View File

@ -22,7 +22,7 @@ import {
AuxRoute, AuxRoute,
AsyncRoute, AsyncRoute,
Redirect Redirect
} from 'angular2/src/router/route_config_decorator'; } from 'angular2/src/router/route_config/route_config_decorator';
import {TEST_ROUTER_PROVIDERS, RootCmp, compile} from './util'; import {TEST_ROUTER_PROVIDERS, RootCmp, compile} from './util';
import {HelloCmp, GoodbyeCmp, RedirectToParentCmp} from './impl/fixture_components'; import {HelloCmp, GoodbyeCmp, RedirectToParentCmp} from './impl/fixture_components';

View File

@ -43,7 +43,7 @@ import {RootRouter} from 'angular2/src/router/router';
import {DOM} from 'angular2/src/platform/dom/dom_adapter'; import {DOM} from 'angular2/src/platform/dom/dom_adapter';
import {TEMPLATE_TRANSFORMS} from 'angular2/compiler'; import {TEMPLATE_TRANSFORMS} from 'angular2/compiler';
import {RouterLinkTransform} from 'angular2/src/router/router_link_transform'; import {RouterLinkTransform} from 'angular2/src/router/directives/router_link_transform';
export function main() { export function main() {
describe('routerLink directive', function() { describe('routerLink directive', function() {

View File

@ -21,7 +21,7 @@ import {RootRouter} from 'angular2/src/router/router';
import {Router, ROUTER_DIRECTIVES, ROUTER_PRIMARY_COMPONENT} from 'angular2/router'; import {Router, ROUTER_DIRECTIVES, ROUTER_PRIMARY_COMPONENT} from 'angular2/router';
import {SpyLocation} from 'angular2/src/mock/location_mock'; import {SpyLocation} from 'angular2/src/mock/location_mock';
import {Location} from 'angular2/src/router/location'; import {Location} from 'angular2/src/router/location/location';
import {RouteRegistry} from 'angular2/src/router/route_registry'; import {RouteRegistry} from 'angular2/src/router/route_registry';
import {DirectiveResolver} from 'angular2/src/core/linker/directive_resolver'; import {DirectiveResolver} from 'angular2/src/core/linker/directive_resolver';
import {DOM} from 'angular2/src/platform/dom/dom_adapter'; import {DOM} from 'angular2/src/platform/dom/dom_adapter';

View File

@ -14,10 +14,10 @@ import {
import {Injector, provide} from 'angular2/core'; import {Injector, provide} from 'angular2/core';
import {PlatformLocation} from 'angular2/src/router/platform_location'; import {PlatformLocation} from 'angular2/src/router/location/platform_location';
import {APP_BASE_HREF} from 'angular2/src/router/location_strategy'; import {APP_BASE_HREF} from 'angular2/src/router/location/location_strategy';
import {HashLocationStrategy} from 'angular2/src/router/hash_location_strategy'; import {HashLocationStrategy} from 'angular2/src/router/location/hash_location_strategy';
import {SpyPlatformLocation} from './spies'; import {SpyPlatformLocation} from '../spies';
export function main() { export function main() {
describe('HashLocationStrategy', () => { describe('HashLocationStrategy', () => {

View File

@ -15,8 +15,8 @@ import {
import {Injector, provide} from 'angular2/core'; import {Injector, provide} from 'angular2/core';
import {CONST_EXPR} from 'angular2/src/facade/lang'; import {CONST_EXPR} from 'angular2/src/facade/lang';
import {Location} from 'angular2/src/router/location'; import {Location} from 'angular2/src/router/location/location';
import {LocationStrategy, APP_BASE_HREF} from 'angular2/src/router/location_strategy'; import {LocationStrategy, APP_BASE_HREF} from 'angular2/src/router/location/location_strategy';
import {MockLocationStrategy} from 'angular2/src/mock/mock_location_strategy'; import {MockLocationStrategy} from 'angular2/src/mock/mock_location_strategy';
export function main() { export function main() {

View File

@ -15,10 +15,10 @@ import {
import {Injector, provide} from 'angular2/core'; import {Injector, provide} from 'angular2/core';
import {CONST_EXPR} from 'angular2/src/facade/lang'; import {CONST_EXPR} from 'angular2/src/facade/lang';
import {PlatformLocation} from 'angular2/src/router/platform_location'; import {PlatformLocation} from 'angular2/src/router/location/platform_location';
import {LocationStrategy, APP_BASE_HREF} from 'angular2/src/router/location_strategy'; import {LocationStrategy, APP_BASE_HREF} from 'angular2/src/router/location/location_strategy';
import {PathLocationStrategy} from 'angular2/src/router/path_location_strategy'; import {PathLocationStrategy} from 'angular2/src/router/location/path_location_strategy';
import {SpyPlatformLocation} from './spies'; import {SpyPlatformLocation} from '../spies';
export function main() { export function main() {
describe('PathLocationStrategy', () => { describe('PathLocationStrategy', () => {

View File

@ -28,7 +28,7 @@ import {
} from 'angular2/router'; } from 'angular2/router';
import {ExceptionHandler} from 'angular2/src/facade/exceptions'; import {ExceptionHandler} from 'angular2/src/facade/exceptions';
import {LocationStrategy} from 'angular2/src/router/location_strategy'; import {LocationStrategy} from 'angular2/src/router/location/location_strategy';
import {MockLocationStrategy} from 'angular2/src/mock/mock_location_strategy'; import {MockLocationStrategy} from 'angular2/src/mock/mock_location_strategy';
class _ArrayLogger { class _ArrayLogger {

View File

@ -20,7 +20,7 @@ import {
Redirect, Redirect,
AuxRoute, AuxRoute,
AsyncRoute AsyncRoute
} from 'angular2/src/router/route_config_decorator'; } from 'angular2/src/router/route_config/route_config_decorator';
export function main() { export function main() {

View File

@ -18,10 +18,15 @@ import {ListWrapper} from 'angular2/src/facade/collection';
import {Router, RootRouter} from 'angular2/src/router/router'; import {Router, RootRouter} from 'angular2/src/router/router';
import {SpyLocation} from 'angular2/src/mock/location_mock'; import {SpyLocation} from 'angular2/src/mock/location_mock';
import {Location} from 'angular2/src/router/location'; import {Location} from 'angular2/src/router/location/location';
import {RouteRegistry, ROUTER_PRIMARY_COMPONENT} from 'angular2/src/router/route_registry'; import {RouteRegistry, ROUTER_PRIMARY_COMPONENT} from 'angular2/src/router/route_registry';
import {RouteConfig, AsyncRoute, Route, Redirect} from 'angular2/src/router/route_config_decorator'; import {
RouteConfig,
AsyncRoute,
Route,
Redirect
} from 'angular2/src/router/route_config/route_config_decorator';
import {DirectiveResolver} from 'angular2/src/core/linker/directive_resolver'; import {DirectiveResolver} from 'angular2/src/core/linker/directive_resolver';
import {provide} from 'angular2/core'; import {provide} from 'angular2/core';

View File

@ -10,93 +10,93 @@ import {
SpyObject SpyObject
} from 'angular2/testing_internal'; } from 'angular2/testing_internal';
import {PathRecognizer} from 'angular2/src/router/path_recognizer'; import {ParamRoutePath} from 'angular2/src/router/rules/route_paths/param_route_path';
import {parser, Url, RootUrl} from 'angular2/src/router/url_parser'; import {parser, Url} from 'angular2/src/router/url_parser';
export function main() { export function main() {
describe('PathRecognizer', () => { describe('PathRecognizer', () => {
it('should throw when given an invalid path', () => { it('should throw when given an invalid path', () => {
expect(() => new PathRecognizer('/hi#')) expect(() => new ParamRoutePath('/hi#'))
.toThrowError(`Path "/hi#" should not include "#". Use "HashLocationStrategy" instead.`); .toThrowError(`Path "/hi#" should not include "#". Use "HashLocationStrategy" instead.`);
expect(() => new PathRecognizer('hi?')) expect(() => new ParamRoutePath('hi?'))
.toThrowError(`Path "hi?" contains "?" which is not allowed in a route config.`); .toThrowError(`Path "hi?" contains "?" which is not allowed in a route config.`);
expect(() => new PathRecognizer('hi;')) expect(() => new ParamRoutePath('hi;'))
.toThrowError(`Path "hi;" contains ";" which is not allowed in a route config.`); .toThrowError(`Path "hi;" contains ";" which is not allowed in a route config.`);
expect(() => new PathRecognizer('hi=')) expect(() => new ParamRoutePath('hi='))
.toThrowError(`Path "hi=" contains "=" which is not allowed in a route config.`); .toThrowError(`Path "hi=" contains "=" which is not allowed in a route config.`);
expect(() => new PathRecognizer('hi(')) expect(() => new ParamRoutePath('hi('))
.toThrowError(`Path "hi(" contains "(" which is not allowed in a route config.`); .toThrowError(`Path "hi(" contains "(" which is not allowed in a route config.`);
expect(() => new PathRecognizer('hi)')) expect(() => new ParamRoutePath('hi)'))
.toThrowError(`Path "hi)" contains ")" which is not allowed in a route config.`); .toThrowError(`Path "hi)" contains ")" which is not allowed in a route config.`);
expect(() => new PathRecognizer('hi//there')) expect(() => new ParamRoutePath('hi//there'))
.toThrowError(`Path "hi//there" contains "//" which is not allowed in a route config.`); .toThrowError(`Path "hi//there" contains "//" which is not allowed in a route config.`);
}); });
describe('querystring params', () => { describe('querystring params', () => {
it('should parse querystring params so long as the recognizer is a root', () => { it('should parse querystring params so long as the recognizer is a root', () => {
var rec = new PathRecognizer('/hello/there'); var rec = new ParamRoutePath('/hello/there');
var url = parser.parse('/hello/there?name=igor'); var url = parser.parse('/hello/there?name=igor');
var match = rec.recognize(url); var match = rec.matchUrl(url);
expect(match['allParams']).toEqual({'name': 'igor'}); expect(match.allParams).toEqual({'name': 'igor'});
}); });
it('should return a combined map of parameters with the param expected in the URL path', it('should return a combined map of parameters with the param expected in the URL path',
() => { () => {
var rec = new PathRecognizer('/hello/:name'); var rec = new ParamRoutePath('/hello/:name');
var url = parser.parse('/hello/paul?topic=success'); var url = parser.parse('/hello/paul?topic=success');
var match = rec.recognize(url); var match = rec.matchUrl(url);
expect(match['allParams']).toEqual({'name': 'paul', 'topic': 'success'}); expect(match.allParams).toEqual({'name': 'paul', 'topic': 'success'});
}); });
}); });
describe('matrix params', () => { describe('matrix params', () => {
it('should be parsed along with dynamic paths', () => { it('should be parsed along with dynamic paths', () => {
var rec = new PathRecognizer('/hello/:id'); var rec = new ParamRoutePath('/hello/:id');
var url = new Url('hello', new Url('matias', null, null, {'key': 'value'})); var url = new Url('hello', new Url('matias', null, null, {'key': 'value'}));
var match = rec.recognize(url); var match = rec.matchUrl(url);
expect(match['allParams']).toEqual({'id': 'matias', 'key': 'value'}); expect(match.allParams).toEqual({'id': 'matias', 'key': 'value'});
}); });
it('should be parsed on a static path', () => { it('should be parsed on a static path', () => {
var rec = new PathRecognizer('/person'); var rec = new ParamRoutePath('/person');
var url = new Url('person', null, null, {'name': 'dave'}); var url = new Url('person', null, null, {'name': 'dave'});
var match = rec.recognize(url); var match = rec.matchUrl(url);
expect(match['allParams']).toEqual({'name': 'dave'}); expect(match.allParams).toEqual({'name': 'dave'});
}); });
it('should be ignored on a wildcard segment', () => { it('should be ignored on a wildcard segment', () => {
var rec = new PathRecognizer('/wild/*everything'); var rec = new ParamRoutePath('/wild/*everything');
var url = parser.parse('/wild/super;variable=value'); var url = parser.parse('/wild/super;variable=value');
var match = rec.recognize(url); var match = rec.matchUrl(url);
expect(match['allParams']).toEqual({'everything': 'super;variable=value'}); expect(match.allParams).toEqual({'everything': 'super;variable=value'});
}); });
it('should set matrix param values to true when no value is present', () => { it('should set matrix param values to true when no value is present', () => {
var rec = new PathRecognizer('/path'); var rec = new ParamRoutePath('/path');
var url = new Url('path', null, null, {'one': true, 'two': true, 'three': '3'}); var url = new Url('path', null, null, {'one': true, 'two': true, 'three': '3'});
var match = rec.recognize(url); var match = rec.matchUrl(url);
expect(match['allParams']).toEqual({'one': true, 'two': true, 'three': '3'}); expect(match.allParams).toEqual({'one': true, 'two': true, 'three': '3'});
}); });
it('should be parsed on the final segment of the path', () => { it('should be parsed on the final segment of the path', () => {
var rec = new PathRecognizer('/one/two/three'); var rec = new ParamRoutePath('/one/two/three');
var three = new Url('three', null, null, {'c': '3'}); var three = new Url('three', null, null, {'c': '3'});
var two = new Url('two', three, null, {'b': '2'}); var two = new Url('two', three, null, {'b': '2'});
var one = new Url('one', two, null, {'a': '1'}); var one = new Url('one', two, null, {'a': '1'});
var match = rec.recognize(one); var match = rec.matchUrl(one);
expect(match['allParams']).toEqual({'c': '3'}); expect(match.allParams).toEqual({'c': '3'});
}); });
}); });
describe('wildcard segment', () => { describe('wildcard segment', () => {
it('should return a url path which matches the original url path', () => { it('should return a url path which matches the original url path', () => {
var rec = new PathRecognizer('/wild/*everything'); var rec = new ParamRoutePath('/wild/*everything');
var url = parser.parse('/wild/super;variable=value/anotherPartAfterSlash'); var url = parser.parse('/wild/super;variable=value/anotherPartAfterSlash');
var match = rec.recognize(url); var match = rec.matchUrl(url);
expect(match['urlPath']).toEqual('wild/super;variable=value/anotherPartAfterSlash'); expect(match.urlPath).toEqual('wild/super;variable=value/anotherPartAfterSlash');
}); });
}); });
}); });

View File

@ -0,0 +1,51 @@
import {
AsyncTestCompleter,
describe,
it,
iit,
ddescribe,
expect,
inject,
beforeEach,
SpyObject
} from 'angular2/testing_internal';
import {GeneratedUrl} from 'angular2/src/router/rules/route_paths/route_path';
import {RegexRoutePath} from 'angular2/src/router/rules/route_paths/regex_route_path';
import {parser, Url} from 'angular2/src/router/url_parser';
function emptySerializer(params) {
return new GeneratedUrl('', {});
}
export function main() {
describe('RegexRoutePath', () => {
it('should throw when given an invalid regex',
() => { expect(() => new RegexRoutePath('[abc', emptySerializer)).toThrowError(); });
it('should parse a single param using capture groups', () => {
var rec = new RegexRoutePath('^(.+)$', emptySerializer);
var url = parser.parse('hello');
var match = rec.matchUrl(url);
expect(match.allParams).toEqual({'0': 'hello', '1': 'hello'});
});
it('should parse multiple params using capture groups', () => {
var rec = new RegexRoutePath('^(.+)\\.(.+)$', emptySerializer);
var url = parser.parse('hello.goodbye');
var match = rec.matchUrl(url);
expect(match.allParams).toEqual({'0': 'hello.goodbye', '1': 'hello', '2': 'goodbye'});
});
it('should generate a url by calling the provided serializer', () => {
function serializer(params) {
return new GeneratedUrl(`/a/${params['a']}/b/${params['b']}`, {});
}
var rec = new RegexRoutePath('/a/(.+)/b/(.+)$', serializer);
var params = {a: 'one', b: 'two'};
var url = rec.generateUrl(params);
expect(url.urlPath).toEqual('/a/one/b/two');
});
});
}

View File

@ -12,19 +12,20 @@ import {
import {Map, StringMapWrapper} from 'angular2/src/facade/collection'; import {Map, StringMapWrapper} from 'angular2/src/facade/collection';
import {RouteMatch, PathMatch, RedirectMatch} from 'angular2/src/router/route_recognizer'; import {RouteMatch, PathMatch, RedirectMatch} from 'angular2/src/router/rules/rules';
import {ComponentRecognizer} from 'angular2/src/router/component_recognizer'; import {RuleSet} from 'angular2/src/router/rules/rule_set';
import {GeneratedUrl} from 'angular2/src/router/rules/route_paths/route_path';
import {Route, Redirect} from 'angular2/src/router/route_config_decorator'; import {Route, Redirect} from 'angular2/src/router/route_config/route_config_decorator';
import {parser} from 'angular2/src/router/url_parser'; import {parser} from 'angular2/src/router/url_parser';
import {PromiseWrapper} from 'angular2/src/facade/promise'; import {PromiseWrapper} from 'angular2/src/facade/promise';
export function main() { export function main() {
describe('ComponentRecognizer', () => { describe('RuleSet', () => {
var recognizer: ComponentRecognizer; var recognizer: RuleSet;
beforeEach(() => { recognizer = new ComponentRecognizer(); }); beforeEach(() => { recognizer = new RuleSet(); });
it('should recognize a static segment', inject([AsyncTestCompleter], (async) => { it('should recognize a static segment', inject([AsyncTestCompleter], (async) => {
@ -72,6 +73,21 @@ export function main() {
}); });
})); }));
it('should recognize a regex', inject([AsyncTestCompleter], (async) => {
function emptySerializer(params): GeneratedUrl { return new GeneratedUrl('', {}); }
recognizer.config(
new Route({regex: '^(.+)/(.+)$', serializer: emptySerializer, component: DummyCmpA}));
recognize(recognizer, '/first/second')
.then((solutions: RouteMatch[]) => {
expect(solutions.length).toBe(1);
expect(getComponentType(solutions[0])).toEqual(DummyCmpA);
expect(getParams(solutions[0]))
.toEqual({'0': 'first/second', '1': 'first', '2': 'second'});
async.done();
});
}));
it('should throw when given two routes that start with the same static segment', () => { it('should throw when given two routes that start with the same static segment', () => {
recognizer.config(new Route({path: '/hello', component: DummyCmpA})); recognizer.config(new Route({path: '/hello', component: DummyCmpA}));
@ -123,6 +139,25 @@ export function main() {
}); });
it('should generate using a serializer', () => {
function simpleSerializer(params): GeneratedUrl {
var extra = {c: params['c']};
return new GeneratedUrl(`/${params['a']}/${params['b']}`, extra);
}
recognizer.config(new Route({
name: 'Route1',
regex: '^(.+)/(.+)$',
serializer: simpleSerializer,
component: DummyCmpA
}));
var params = {a: 'first', b: 'second', c: 'third'};
var result = recognizer.generate('Route1', params);
expect(result.urlPath).toEqual('/first/second');
expect(result.urlParams).toEqual(['c=third']);
});
it('should throw in the absence of required params URLs', () => { it('should throw in the absence of required params URLs', () => {
recognizer.config(new Route({path: 'app/user/:name', component: DummyCmpA, name: 'User'})); recognizer.config(new Route({path: 'app/user/:name', component: DummyCmpA, name: 'User'}));
expect(() => recognizer.generate('User', {})) expect(() => recognizer.generate('User', {}))
@ -193,7 +228,7 @@ export function main() {
}); });
} }
function recognize(recognizer: ComponentRecognizer, url: string): Promise<RouteMatch[]> { function recognize(recognizer: RuleSet, url: string): Promise<RouteMatch[]> {
var parsedUrl = parser.parse(url); var parsedUrl = parser.parse(url);
return PromiseWrapper.all(recognizer.recognize(parsedUrl)); return PromiseWrapper.all(recognizer.recognize(parsedUrl));
} }

View File

@ -15,7 +15,7 @@ import {UrlParser, Url} from 'angular2/src/router/url_parser';
export function main() { export function main() {
describe('ParsedUrl', () => { describe('ParsedUrl', () => {
var urlParser; var urlParser: UrlParser;
beforeEach(() => { urlParser = new UrlParser(); }); beforeEach(() => { urlParser = new UrlParser(); });

View File

@ -5,7 +5,7 @@ import {
WORKER_SCRIPT, WORKER_SCRIPT,
WORKER_RENDER_ROUTER WORKER_RENDER_ROUTER
} from 'angular2/platform/worker_render'; } from 'angular2/platform/worker_render';
import {BrowserPlatformLocation} from "angular2/src/router/browser_platform_location"; import {BrowserPlatformLocation} from "angular2/src/router/location/browser_platform_location";
import {MessageBasedPlatformLocation} from "angular2/src/web_workers/ui/platform_location"; import {MessageBasedPlatformLocation} from "angular2/src/web_workers/ui/platform_location";
let ref = platform([WORKER_RENDER_PLATFORM]) let ref = platform([WORKER_RENDER_PLATFORM])

View File

@ -72,7 +72,7 @@ module.exports = function makeNodeTree(projects, destinationPath) {
'angular2/test/common/forms/**', 'angular2/test/common/forms/**',
// we call browser's bootstrap // we call browser's bootstrap
'angular2/test/router/route_config_spec.ts', 'angular2/test/router/route_config/route_config_spec.ts',
'angular2/test/router/integration/bootstrap_spec.ts', 'angular2/test/router/integration/bootstrap_spec.ts',
// we check the public api by importing angular2/angular2 // we check the public api by importing angular2/angular2