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

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

View File

@ -15,8 +15,8 @@ import {
import {Injector, provide} from 'angular2/core';
import {CONST_EXPR} from 'angular2/src/facade/lang';
import {parseRouterLinkExpression} from 'angular2/src/router/router_link_transform';
import {Unparser} from '../core/change_detection/parser/unparser';
import {parseRouterLinkExpression} from 'angular2/src/router/directives/router_link_transform';
import {Unparser} from '../../core/change_detection/parser/unparser';
import {Parser} from 'angular2/src/core/change_detection/parser/parser';
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 {provide, ViewChild, AfterViewInit} from 'angular2/core';
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 {BaseException, WrappedException} from 'angular2/src/facade/exceptions';
import {

View File

@ -19,7 +19,12 @@ import {By} from 'angular2/platform/common_dom';
import {provide, Component, Injector, Inject} from 'angular2/core';
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 {BaseException} from 'angular2/src/facade/exceptions';

View File

@ -31,7 +31,7 @@ import {
AuxRoute,
AsyncRoute,
Redirect
} from 'angular2/src/router/route_config_decorator';
} from 'angular2/src/router/route_config/route_config_decorator';
import {
OnActivate,
@ -40,7 +40,7 @@ import {
CanDeactivate,
CanReuse
} 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';

View File

@ -25,7 +25,7 @@ import {
AuxRoute,
AsyncRoute,
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';

View File

@ -22,7 +22,7 @@ import {
AuxRoute,
AsyncRoute,
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 {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 {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() {
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 {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 {DirectiveResolver} from 'angular2/src/core/linker/directive_resolver';
import {DOM} from 'angular2/src/platform/dom/dom_adapter';

View File

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

View File

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

View File

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

View File

@ -28,7 +28,7 @@ import {
} from 'angular2/router';
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';
class _ArrayLogger {

View File

@ -20,7 +20,7 @@ import {
Redirect,
AuxRoute,
AsyncRoute
} from 'angular2/src/router/route_config_decorator';
} from 'angular2/src/router/route_config/route_config_decorator';
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 {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 {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 {provide} from 'angular2/core';

View File

@ -10,93 +10,93 @@ import {
SpyObject
} from 'angular2/testing_internal';
import {PathRecognizer} from 'angular2/src/router/path_recognizer';
import {parser, Url, RootUrl} from 'angular2/src/router/url_parser';
import {ParamRoutePath} from 'angular2/src/router/rules/route_paths/param_route_path';
import {parser, Url} from 'angular2/src/router/url_parser';
export function main() {
describe('PathRecognizer', () => {
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.`);
expect(() => new PathRecognizer('hi?'))
expect(() => new ParamRoutePath('hi?'))
.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.`);
expect(() => new PathRecognizer('hi='))
expect(() => new ParamRoutePath('hi='))
.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.`);
expect(() => new PathRecognizer('hi)'))
expect(() => new ParamRoutePath('hi)'))
.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.`);
});
describe('querystring params', () => {
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 match = rec.recognize(url);
expect(match['allParams']).toEqual({'name': 'igor'});
var match = rec.matchUrl(url);
expect(match.allParams).toEqual({'name': 'igor'});
});
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 match = rec.recognize(url);
expect(match['allParams']).toEqual({'name': 'paul', 'topic': 'success'});
var match = rec.matchUrl(url);
expect(match.allParams).toEqual({'name': 'paul', 'topic': 'success'});
});
});
describe('matrix params', () => {
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 match = rec.recognize(url);
expect(match['allParams']).toEqual({'id': 'matias', 'key': 'value'});
var match = rec.matchUrl(url);
expect(match.allParams).toEqual({'id': 'matias', 'key': 'value'});
});
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 match = rec.recognize(url);
expect(match['allParams']).toEqual({'name': 'dave'});
var match = rec.matchUrl(url);
expect(match.allParams).toEqual({'name': 'dave'});
});
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 match = rec.recognize(url);
expect(match['allParams']).toEqual({'everything': 'super;variable=value'});
var match = rec.matchUrl(url);
expect(match.allParams).toEqual({'everything': 'super;variable=value'});
});
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 match = rec.recognize(url);
expect(match['allParams']).toEqual({'one': true, 'two': true, 'three': '3'});
var match = rec.matchUrl(url);
expect(match.allParams).toEqual({'one': true, 'two': true, 'three': '3'});
});
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 two = new Url('two', three, null, {'b': '2'});
var one = new Url('one', two, null, {'a': '1'});
var match = rec.recognize(one);
expect(match['allParams']).toEqual({'c': '3'});
var match = rec.matchUrl(one);
expect(match.allParams).toEqual({'c': '3'});
});
});
describe('wildcard segment', () => {
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 match = rec.recognize(url);
expect(match['urlPath']).toEqual('wild/super;variable=value/anotherPartAfterSlash');
var match = rec.matchUrl(url);
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 {RouteMatch, PathMatch, RedirectMatch} from 'angular2/src/router/route_recognizer';
import {ComponentRecognizer} from 'angular2/src/router/component_recognizer';
import {RouteMatch, PathMatch, RedirectMatch} from 'angular2/src/router/rules/rules';
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 {PromiseWrapper} from 'angular2/src/facade/promise';
export function main() {
describe('ComponentRecognizer', () => {
var recognizer: ComponentRecognizer;
describe('RuleSet', () => {
var recognizer: RuleSet;
beforeEach(() => { recognizer = new ComponentRecognizer(); });
beforeEach(() => { recognizer = new RuleSet(); });
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', () => {
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', () => {
recognizer.config(new Route({path: 'app/user/:name', component: DummyCmpA, name: '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);
return PromiseWrapper.all(recognizer.recognize(parsedUrl));
}

View File

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