From 149a7044d5640bbb0da0ccb56cef1f821368cde5 Mon Sep 17 00:00:00 2001 From: Peter Bacon Darwin Date: Wed, 10 Feb 2016 17:00:34 -0800 Subject: [PATCH 01/43] fix(angular1_router): rename `router` component binding to `$router` The current router is passed to the current component via a binding. To indicate that this is an angular provided object, this commit renames the binding to `$router`. BREAKING CHANGE: The recently added binding of the current router to the current component has been renamed from `router` to `$router`. So now the recommended set up for your bindings in your routed component is: ```js { ... bindings: { $router: '<' } } ``` --- modules/angular1_router/test/integration/router_spec.js | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/modules/angular1_router/test/integration/router_spec.js b/modules/angular1_router/test/integration/router_spec.js index 9ef4224545d8..81218edeb4a1 100644 --- a/modules/angular1_router/test/integration/router_spec.js +++ b/modules/angular1_router/test/integration/router_spec.js @@ -139,12 +139,8 @@ describe('router', function () { bindings: options.bindings, controller: getController(options), }; - if (options.template) { - definition.template = options.template; - } - if (options.templateUrl) { - definition.templateUrl = options.templateUrl; - } + if (options.template) definition.template = options.template; + if (options.templateUrl) definition.templateUrl = options.templateUrl; applyStaticProperties(definition, options); $compileProvider.component(name, definition); From d23ecd8235ce6da9aca9c4fb1f95096e25ecba2d Mon Sep 17 00:00:00 2001 From: Peter Bacon Darwin Date: Wed, 10 Feb 2016 16:59:26 -0800 Subject: [PATCH 02/43] fix(angular1_router): support templateUrl components --- modules/angular1_router/src/ng_outlet.ts | 1 + modules/angular1_router/test/integration/router_spec.js | 8 ++++++-- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/modules/angular1_router/src/ng_outlet.ts b/modules/angular1_router/src/ng_outlet.ts index f6e346014a93..273a6ffd6a14 100644 --- a/modules/angular1_router/src/ng_outlet.ts +++ b/modules/angular1_router/src/ng_outlet.ts @@ -200,6 +200,7 @@ function ngOutletFillContentDirective($compile) { + function routerTriggerDirective($q) { return { require: '^ngOutlet', diff --git a/modules/angular1_router/test/integration/router_spec.js b/modules/angular1_router/test/integration/router_spec.js index 81218edeb4a1..9ef4224545d8 100644 --- a/modules/angular1_router/test/integration/router_spec.js +++ b/modules/angular1_router/test/integration/router_spec.js @@ -139,8 +139,12 @@ describe('router', function () { bindings: options.bindings, controller: getController(options), }; - if (options.template) definition.template = options.template; - if (options.templateUrl) definition.templateUrl = options.templateUrl; + if (options.template) { + definition.template = options.template; + } + if (options.templateUrl) { + definition.templateUrl = options.templateUrl; + } applyStaticProperties(definition, options); $compileProvider.component(name, definition); From fea4518d114cd5299c8648a4f453a8b3516cbdee Mon Sep 17 00:00:00 2001 From: Peter Bacon Darwin Date: Wed, 10 Feb 2016 17:00:34 -0800 Subject: [PATCH 03/43] fix(angular1_router): rename `router` component binding to `$router` The current router is passed to the current component via a binding. To indicate that this is an angular provided object, this commit renames the binding to `$router`. BREAKING CHANGE: The recently added binding of the current router to the current component has been renamed from `router` to `$router`. So now the recommended set up for your bindings in your routed component is: ```js { ... bindings: { $router: '<' } } ``` --- modules/angular1_router/test/integration/router_spec.js | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/modules/angular1_router/test/integration/router_spec.js b/modules/angular1_router/test/integration/router_spec.js index 9ef4224545d8..81218edeb4a1 100644 --- a/modules/angular1_router/test/integration/router_spec.js +++ b/modules/angular1_router/test/integration/router_spec.js @@ -139,12 +139,8 @@ describe('router', function () { bindings: options.bindings, controller: getController(options), }; - if (options.template) { - definition.template = options.template; - } - if (options.templateUrl) { - definition.templateUrl = options.templateUrl; - } + if (options.template) definition.template = options.template; + if (options.templateUrl) definition.templateUrl = options.templateUrl; applyStaticProperties(definition, options); $compileProvider.component(name, definition); From 47d544487c4e9d30d4c4acea8d91c30ddea9fb7a Mon Sep 17 00:00:00 2001 From: Brian Ford Date: Tue, 9 Feb 2016 11:12:41 -0800 Subject: [PATCH 04/43] wip: feat(router): add regex matchers --- .../angular2/src/router/path_recognizer.ts | 68 +++++++++++++++++-- .../angular2/src/router/route_definition.ts | 3 + .../angular2/src/router/route_recognizer.ts | 12 ++-- .../test/router/path_recognizer_spec.ts | 16 ++--- .../test/router/regex_recognizer_spec.ts | 42 ++++++++++++ 5 files changed, 122 insertions(+), 19 deletions(-) create mode 100644 modules/angular2/test/router/regex_recognizer_spec.ts diff --git a/modules/angular2/src/router/path_recognizer.ts b/modules/angular2/src/router/path_recognizer.ts index 36a1cd88878c..89baf2961f1b 100644 --- a/modules/angular2/src/router/path_recognizer.ts +++ b/modules/angular2/src/router/path_recognizer.ts @@ -171,16 +171,73 @@ function assertPath(path: string) { } } +export class RecognizedUrlSegment { + constructor( + public urlPath: string, + public urlParams: string[], + public allParams: {[key: string]: string}, + public auxiliary: Url[], + public nextSegment: Url) {} +} + +export class GeneratedUrlSegment { + constructor(public urlPath: string, public urlParams: string[]) {} +} + +export interface Recognizer { + specificity: string; + terminal: boolean; + hash: string; + + recognize(beginningSegment: Url): RecognizedUrlSegment; + generate(params: {[key: string]: any}): GeneratedUrlSegment; +} + +export class RegexRecognizer implements Recognizer { + public hash: string; + public terminal: boolean = true; + public specificity: string = '2'; + private _regex: RegExp; + + constructor(private _reString: string, private _serializer: (params: {[key: string]: any}) => GeneratedUrlSegment) { + this.hash = this._reString; + this._regex = RegExpWrapper.create(this._reString); + } + + recognize(beginningSegment: Url): RecognizedUrlSegment { + var url = beginningSegment.toString(); + var match = RegExpWrapper.firstMatch(this._regex, url); + + if (isBlank(match)) { + return null; + } + + var params : {[key: string]: string} = {}; + + for (let i = 0; i < match.length; i += 1) { + params[i.toString()] = match[i]; + } + + return new RecognizedUrlSegment(url, [], params, [], null); + } + + generate(params: {[key: string]: any}): GeneratedUrlSegment { + return this._serializer(params); + } +} /** * Parses a URL string using a given matcher DSL, and generates URLs from param maps */ -export class PathRecognizer { +export class PathRecognizer implements Recognizer { private _segments: Segment[]; specificity: string; terminal: boolean = true; hash: string; + /** + * Takes a string representing the matcher DSL + */ constructor(public path: string) { assertPath(path); var parsed = parsePathString(path); @@ -193,7 +250,7 @@ export class PathRecognizer { this.terminal = !(lastSegment instanceof ContinuationSegment); } - recognize(beginningSegment: Url): {[key: string]: any} { + recognize(beginningSegment: Url): RecognizedUrlSegment { var nextSegment = beginningSegment; var currentSegment: Url; var positionalParams = {}; @@ -256,11 +313,12 @@ export class PathRecognizer { auxiliary = []; urlParams = []; } - return {urlPath, urlParams, allParams, auxiliary, nextSegment}; + + return new RecognizedUrlSegment(urlPath, urlParams, allParams, auxiliary, nextSegment); } - generate(params: {[key: string]: any}): {[key: string]: any} { + generate(params: {[key: string]: any}): GeneratedUrlSegment { var paramTokens = new TouchMap(params); var path = []; @@ -276,6 +334,6 @@ export class PathRecognizer { var nonPositionalParams = paramTokens.getUnused(); var urlParams = serializeParams(nonPositionalParams); - return {urlPath, urlParams}; + return new GeneratedUrlSegment(urlPath, urlParams); } } diff --git a/modules/angular2/src/router/route_definition.ts b/modules/angular2/src/router/route_definition.ts index c34c27815801..fb58f5e8dfd1 100644 --- a/modules/angular2/src/router/route_definition.ts +++ b/modules/angular2/src/router/route_definition.ts @@ -14,6 +14,9 @@ import {CONST, Type} from 'angular2/src/facade/lang'; export interface RouteDefinition { path?: string; aux?: string; + regex?: string; + //TODO: + //serializer?: component?: Type | ComponentDefinition; loader?: Function; redirectTo?: any[]; diff --git a/modules/angular2/src/router/route_recognizer.ts b/modules/angular2/src/router/route_recognizer.ts index 266d12b8b337..1aa80a7590dd 100644 --- a/modules/angular2/src/router/route_recognizer.ts +++ b/modules/angular2/src/router/route_recognizer.ts @@ -6,7 +6,7 @@ import {Map} from 'angular2/src/facade/collection'; import {RouteHandler} from './route_handler'; import {Url} from './url_parser'; import {ComponentInstruction} from './instruction'; -import {PathRecognizer} from './path_recognizer'; +import {PathRecognizer, GeneratedUrlSegment} from './path_recognizer'; export abstract class RouteMatch {} @@ -83,19 +83,19 @@ export class RouteRecognizer implements AbstractRecognizer { return this.handler.resolveComponentType().then((_) => { var componentInstruction = - this._getInstruction(res['urlPath'], res['urlParams'], res['allParams']); - return new PathMatch(componentInstruction, res['nextSegment'], res['auxiliary']); + this._getInstruction(res.urlPath, res.urlParams, res.allParams); + return new PathMatch(componentInstruction, res.nextSegment, res.auxiliary); }); } generate(params: {[key: string]: any}): ComponentInstruction { var generated = this._pathRecognizer.generate(params); - var urlPath = generated['urlPath']; - var urlParams = generated['urlParams']; + var urlPath = generated.urlPath; + var urlParams = generated.urlParams; return this._getInstruction(urlPath, urlParams, params); } - generateComponentPathValues(params: {[key: string]: any}): {[key: string]: any} { + generateComponentPathValues(params: {[key: string]: any}): GeneratedUrlSegment { return this._pathRecognizer.generate(params); } diff --git a/modules/angular2/test/router/path_recognizer_spec.ts b/modules/angular2/test/router/path_recognizer_spec.ts index c0acfc59c791..ec54d8af260e 100644 --- a/modules/angular2/test/router/path_recognizer_spec.ts +++ b/modules/angular2/test/router/path_recognizer_spec.ts @@ -11,7 +11,7 @@ import { } from 'angular2/testing_internal'; import {PathRecognizer} from 'angular2/src/router/path_recognizer'; -import {parser, Url, RootUrl} from 'angular2/src/router/url_parser'; +import {parser, Url} from 'angular2/src/router/url_parser'; export function main() { describe('PathRecognizer', () => { @@ -38,7 +38,7 @@ export function main() { var rec = new PathRecognizer('/hello/there'); var url = parser.parse('/hello/there?name=igor'); var match = rec.recognize(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', @@ -46,7 +46,7 @@ export function main() { var rec = new PathRecognizer('/hello/:name'); var url = parser.parse('/hello/paul?topic=success'); var match = rec.recognize(url); - expect(match['allParams']).toEqual({'name': 'paul', 'topic': 'success'}); + expect(match.allParams).toEqual({'name': 'paul', 'topic': 'success'}); }); }); @@ -55,28 +55,28 @@ export function main() { var rec = new PathRecognizer('/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'}); + expect(match.allParams).toEqual({'id': 'matias', 'key': 'value'}); }); it('should be parsed on a static path', () => { var rec = new PathRecognizer('/person'); var url = new Url('person', null, null, {'name': 'dave'}); var match = rec.recognize(url); - expect(match['allParams']).toEqual({'name': 'dave'}); + expect(match.allParams).toEqual({'name': 'dave'}); }); it('should be ignored on a wildcard segment', () => { var rec = new PathRecognizer('/wild/*everything'); var url = parser.parse('/wild/super;variable=value'); var match = rec.recognize(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', () => { var rec = new PathRecognizer('/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'}); + expect(match.allParams).toEqual({'one': true, 'two': true, 'three': '3'}); }); it('should be parsed on the final segment of the path', () => { @@ -87,7 +87,7 @@ export function main() { var one = new Url('one', two, null, {'a': '1'}); var match = rec.recognize(one); - expect(match['allParams']).toEqual({'c': '3'}); + expect(match.allParams).toEqual({'c': '3'}); }); }); diff --git a/modules/angular2/test/router/regex_recognizer_spec.ts b/modules/angular2/test/router/regex_recognizer_spec.ts new file mode 100644 index 000000000000..9090bd945166 --- /dev/null +++ b/modules/angular2/test/router/regex_recognizer_spec.ts @@ -0,0 +1,42 @@ +import { + AsyncTestCompleter, + describe, + it, + iit, + ddescribe, + expect, + inject, + beforeEach, + SpyObject +} from 'angular2/testing_internal'; + +import {RegexRecognizer, GeneratedUrlSegment} from 'angular2/src/router/path_recognizer'; +import {parser, Url} from 'angular2/src/router/url_parser'; + +export function main() { + describe('RegexRecognizer', () => { + + it('should throw when given an invalid regex', () => { + expect(() => new RegexRecognizer('[abc', emptySerializer)) + .toThrowError(`Regex "[abc" is invalid.`); + }); + + iit('should parse a single param using capture groups', () => { + var rec = new RegexRecognizer('^(.+)$', emptySerializer); + var url = parser.parse('hello'); + var match = rec.recognize(url); + expect(match.allParams).toEqual({ '0': 'hello', '1': 'hello' }); + }); + + iit('should parse multiple params using capture groups', () => { + var rec = new RegexRecognizer('^(.+)\\.(.+)$', emptySerializer); + var url = parser.parse('hello.goodbye'); + var match = rec.recognize(url); + expect(match.allParams).toEqual({ '0': 'hello.goodbye', '1': 'hello', '2': 'goodbye' }); + }); + + function emptySerializer(params) { + return new GeneratedUrlSegment('', []); + } + }); +} From 40f5b9f9c293294bc3514cfbabb110ec58a131e7 Mon Sep 17 00:00:00 2001 From: Peter Bacon Darwin Date: Sun, 14 Feb 2016 15:48:29 +0000 Subject: [PATCH 05/43] test(router): fix expected regex error message --- modules/angular2/test/router/regex_recognizer_spec.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/modules/angular2/test/router/regex_recognizer_spec.ts b/modules/angular2/test/router/regex_recognizer_spec.ts index 9090bd945166..31c6981cfc38 100644 --- a/modules/angular2/test/router/regex_recognizer_spec.ts +++ b/modules/angular2/test/router/regex_recognizer_spec.ts @@ -18,17 +18,17 @@ export function main() { it('should throw when given an invalid regex', () => { expect(() => new RegexRecognizer('[abc', emptySerializer)) - .toThrowError(`Regex "[abc" is invalid.`); + .toThrowError('Invalid regular expression: /[abc/: Unterminated character class'); }); - iit('should parse a single param using capture groups', () => { + it('should parse a single param using capture groups', () => { var rec = new RegexRecognizer('^(.+)$', emptySerializer); var url = parser.parse('hello'); var match = rec.recognize(url); expect(match.allParams).toEqual({ '0': 'hello', '1': 'hello' }); }); - iit('should parse multiple params using capture groups', () => { + it('should parse multiple params using capture groups', () => { var rec = new RegexRecognizer('^(.+)\\.(.+)$', emptySerializer); var url = parser.parse('hello.goodbye'); var match = rec.recognize(url); From 6bcec5c6a91b726ba122b39c7c7ef0df42eee62c Mon Sep 17 00:00:00 2001 From: Peter Bacon Darwin Date: Sun, 14 Feb 2016 15:52:58 +0000 Subject: [PATCH 06/43] refactor(router): rename ComponentRecognizer -> RuleSet --- modules/angular1_router/build.js | 2 +- modules/angular2/src/router/route_registry.ts | 56 +++++++++---------- .../{component_recognizer.ts => rule_set.ts} | 4 +- ...nt_recognizer_spec.ts => rule_set_spec.ts} | 10 ++-- 4 files changed, 36 insertions(+), 36 deletions(-) rename modules/angular2/src/router/{component_recognizer.ts => rule_set.ts} (97%) rename modules/angular2/test/router/{component_recognizer_spec.ts => rule_set_spec.ts} (96%) diff --git a/modules/angular1_router/build.js b/modules/angular1_router/build.js index 2ccf926163f1..1f66b4ef62da 100644 --- a/modules/angular1_router/build.js +++ b/modules/angular1_router/build.js @@ -10,7 +10,7 @@ var files = [ 'route_config_impl.ts', 'async_route_handler.ts', 'sync_route_handler.ts', - 'component_recognizer.ts', + 'rule_set.ts', 'instruction.ts', 'path_recognizer.ts', 'route_config_nomalizer.ts', diff --git a/modules/angular2/src/router/route_registry.ts b/modules/angular2/src/router/route_registry.ts index b441f02a84e2..44a0b7ff627f 100644 --- a/modules/angular2/src/router/route_registry.ts +++ b/modules/angular2/src/router/route_registry.ts @@ -26,7 +26,7 @@ import { RouteDefinition } from './route_config_impl'; import {PathMatch, RedirectMatch, RouteMatch} from './route_recognizer'; -import {ComponentRecognizer} from './component_recognizer'; +import {RuleSet} from './rule_set'; import { Instruction, ResolvedInstruction, @@ -78,7 +78,7 @@ export const ROUTER_PRIMARY_COMPONENT: OpaqueToken = */ @Injectable() export class RouteRegistry { - private _rules = new Map(); + private _rules = new Map(); constructor(@Inject(ROUTER_PRIMARY_COMPONENT) private _rootComponent: Type) {} @@ -95,14 +95,14 @@ export class RouteRegistry { assertComponentExists(config.component, config.path); } - var recognizer: ComponentRecognizer = this._rules.get(parentComponent); + var rules = this._rules.get(parentComponent); - if (isBlank(recognizer)) { - recognizer = new ComponentRecognizer(); - this._rules.set(parentComponent, recognizer); + if (isBlank(rules)) { + rules = new RuleSet(); + this._rules.set(parentComponent, rules); } - var terminal = recognizer.config(config); + var terminal = rules.config(config); if (config instanceof Route) { if (terminal) { @@ -159,15 +159,15 @@ export class RouteRegistry { var parentComponent = isPresent(parentInstruction) ? parentInstruction.component.componentType : this._rootComponent; - var componentRecognizer = this._rules.get(parentComponent); - if (isBlank(componentRecognizer)) { + var rules = this._rules.get(parentComponent); + if (isBlank(rules)) { return _resolveToNull; } // Matches some beginning part of the given URL var possibleMatches: Promise[] = - _aux ? componentRecognizer.recognizeAuxiliary(parsedUrl) : - componentRecognizer.recognize(parsedUrl); + _aux ? rules.recognizeAuxiliary(parsedUrl) : + rules.recognize(parsedUrl); var matchPromises: Promise[] = possibleMatches.map( (candidate: Promise) => candidate.then((candidate: RouteMatch) => { @@ -184,9 +184,9 @@ export class RouteRegistry { 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) => { if (isBlank(childInstruction)) { return null; @@ -359,8 +359,8 @@ export class RouteRegistry { componentInstruction = prevInstruction.component; } - var componentRecognizer = this._rules.get(parentComponentType); - if (isBlank(componentRecognizer)) { + var rules = this._rules.get(parentComponentType); + if (isBlank(rules)) { throw new BaseException( `Component "${getTypeNameForDebugging(parentComponentType)}" has no route config.`); } @@ -383,7 +383,7 @@ export class RouteRegistry { } } var routeRecognizer = - (_aux ? componentRecognizer.auxNames : componentRecognizer.names).get(routeName); + (_aux ? rules.auxNames : rules.names).get(routeName); if (isBlank(routeRecognizer)) { throw new BaseException( @@ -403,8 +403,8 @@ export class RouteRegistry { }, compInstruction['urlPath'], compInstruction['urlParams']); } - componentInstruction = _aux ? componentRecognizer.generateAuxiliary(routeName, routeParams) : - componentRecognizer.generate(routeName, routeParams); + componentInstruction = _aux ? rules.generateAuxiliary(routeName, routeParams) : + rules.generate(routeName, routeParams); } // Next, recognize auxiliary instructions. @@ -442,11 +442,11 @@ export class RouteRegistry { } public hasRoute(name: string, parentComponent: any): boolean { - var componentRecognizer: ComponentRecognizer = this._rules.get(parentComponent); - if (isBlank(componentRecognizer)) { + var rules = this._rules.get(parentComponent); + if (isBlank(rules)) { return false; } - return componentRecognizer.hasRoute(name); + return rules.hasRoute(name); } public generateDefault(componentCursor: Type): Instruction { @@ -454,22 +454,22 @@ export class RouteRegistry { return null; } - var componentRecognizer = this._rules.get(componentCursor); - if (isBlank(componentRecognizer) || isBlank(componentRecognizer.defaultRoute)) { + var rules = this._rules.get(componentCursor); + if (isBlank(rules) || isBlank(rules.defaultRoute)) { return null; } var defaultChild = null; - if (isPresent(componentRecognizer.defaultRoute.handler.componentType)) { - var componentInstruction = componentRecognizer.defaultRoute.generate({}); - if (!componentRecognizer.defaultRoute.terminal) { - defaultChild = this.generateDefault(componentRecognizer.defaultRoute.handler.componentType); + if (isPresent(rules.defaultRoute.handler.componentType)) { + var componentInstruction = rules.defaultRoute.generate({}); + if (!rules.defaultRoute.terminal) { + defaultChild = this.generateDefault(rules.defaultRoute.handler.componentType); } return new DefaultInstruction(componentInstruction, defaultChild); } return new UnresolvedInstruction(() => { - return componentRecognizer.defaultRoute.handler.resolveComponentType().then( + return rules.defaultRoute.handler.resolveComponentType().then( (_) => this.generateDefault(componentCursor)); }); } diff --git a/modules/angular2/src/router/component_recognizer.ts b/modules/angular2/src/router/rule_set.ts similarity index 97% rename from modules/angular2/src/router/component_recognizer.ts rename to modules/angular2/src/router/rule_set.ts index 7d204c218441..1905b954ad10 100644 --- a/modules/angular2/src/router/component_recognizer.ts +++ b/modules/angular2/src/router/rule_set.ts @@ -18,11 +18,11 @@ import {ComponentInstruction} from './instruction'; /** - * `ComponentRecognizer` is responsible for recognizing routes for a single component. + * A `RuleSet` is responsible for recognzing routes for a particular component. * It is consumed by `RouteRegistry`, which knows how to recognize an entire hierarchy of * components. */ -export class ComponentRecognizer { +export class RuleSet { names = new Map(); // map from name to recognizer diff --git a/modules/angular2/test/router/component_recognizer_spec.ts b/modules/angular2/test/router/rule_set_spec.ts similarity index 96% rename from modules/angular2/test/router/component_recognizer_spec.ts rename to modules/angular2/test/router/rule_set_spec.ts index 7e083d030287..5d6043aff733 100644 --- a/modules/angular2/test/router/component_recognizer_spec.ts +++ b/modules/angular2/test/router/rule_set_spec.ts @@ -13,7 +13,7 @@ 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 {RuleSet} from 'angular2/src/router/rule_set'; import {Route, Redirect} from 'angular2/src/router/route_config_decorator'; import {parser} from 'angular2/src/router/url_parser'; @@ -21,10 +21,10 @@ 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) => { @@ -193,7 +193,7 @@ export function main() { }); } -function recognize(recognizer: ComponentRecognizer, url: string): Promise { +function recognize(recognizer: RuleSet, url: string): Promise { var parsedUrl = parser.parse(url); return PromiseWrapper.all(recognizer.recognize(parsedUrl)); } From 00c4ec7ae34555546f17c6356553ee03ff045988 Mon Sep 17 00:00:00 2001 From: Peter Bacon Darwin Date: Sun, 14 Feb 2016 16:21:11 +0000 Subject: [PATCH 07/43] refactor(router): rename route "...Recognizer" classes to "...Rule" --- modules/angular1_router/build.js | 2 +- modules/angular2/src/router/route_registry.ts | 16 ++-- modules/angular2/src/router/rule_set.ts | 76 ++++++++++--------- .../router/{route_recognizer.ts => rules.ts} | 22 +++--- modules/angular2/test/router/rule_set_spec.ts | 2 +- 5 files changed, 60 insertions(+), 58 deletions(-) rename modules/angular2/src/router/{route_recognizer.ts => rules.ts} (92%) diff --git a/modules/angular1_router/build.js b/modules/angular1_router/build.js index 1f66b4ef62da..37f02c39afea 100644 --- a/modules/angular1_router/build.js +++ b/modules/angular1_router/build.js @@ -6,7 +6,7 @@ var ts = require('typescript'); var files = [ 'lifecycle_annotations_impl.ts', 'url_parser.ts', - 'route_recognizer.ts', + 'rules.ts', 'route_config_impl.ts', 'async_route_handler.ts', 'sync_route_handler.ts', diff --git a/modules/angular2/src/router/route_registry.ts b/modules/angular2/src/router/route_registry.ts index 44a0b7ff627f..a66b29046153 100644 --- a/modules/angular2/src/router/route_registry.ts +++ b/modules/angular2/src/router/route_registry.ts @@ -25,7 +25,7 @@ import { Redirect, RouteDefinition } from './route_config_impl'; -import {PathMatch, RedirectMatch, RouteMatch} from './route_recognizer'; +import {PathMatch, RedirectMatch, RouteMatch} from './rules'; import {RuleSet} from './rule_set'; import { Instruction, @@ -383,7 +383,7 @@ export class RouteRegistry { } } var routeRecognizer = - (_aux ? rules.auxNames : rules.names).get(routeName); + (_aux ? rules.auxRulesByName : rules.rulesByName).get(routeName); if (isBlank(routeRecognizer)) { throw new BaseException( @@ -455,21 +455,21 @@ export class RouteRegistry { } var rules = this._rules.get(componentCursor); - if (isBlank(rules) || isBlank(rules.defaultRoute)) { + if (isBlank(rules) || isBlank(rules.defaultRule)) { return null; } var defaultChild = null; - if (isPresent(rules.defaultRoute.handler.componentType)) { - var componentInstruction = rules.defaultRoute.generate({}); - if (!rules.defaultRoute.terminal) { - defaultChild = this.generateDefault(rules.defaultRoute.handler.componentType); + if (isPresent(rules.defaultRule.handler.componentType)) { + var componentInstruction = rules.defaultRule.generate({}); + if (!rules.defaultRule.terminal) { + defaultChild = this.generateDefault(rules.defaultRule.handler.componentType); } return new DefaultInstruction(componentInstruction, defaultChild); } return new UnresolvedInstruction(() => { - return rules.defaultRoute.handler.resolveComponentType().then( + return rules.defaultRule.handler.resolveComponentType().then( (_) => this.generateDefault(componentCursor)); }); } diff --git a/modules/angular2/src/router/rule_set.ts b/modules/angular2/src/router/rule_set.ts index 1905b954ad10..47eacf5e9fe2 100644 --- a/modules/angular2/src/router/rule_set.ts +++ b/modules/angular2/src/router/rule_set.ts @@ -4,12 +4,12 @@ import {Map, MapWrapper, ListWrapper, StringMapWrapper} from 'angular2/src/facad import {PromiseWrapper} from 'angular2/src/facade/async'; import { - AbstractRecognizer, - RouteRecognizer, - RedirectRecognizer, + AbstractRule, + RouteRule, + RedirectRule, RouteMatch, PathMatch -} from './route_recognizer'; +} from './rules'; import {Route, AsyncRoute, AuxRoute, Redirect, RouteDefinition} from './route_config_impl'; import {AsyncRouteHandler} from './async_route_handler'; import {SyncRouteHandler} from './sync_route_handler'; @@ -18,32 +18,34 @@ import {ComponentInstruction} from './instruction'; /** - * A `RuleSet` is responsible for recognzing routes for a particular component. + * 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 { - names = new Map(); + rulesByName = new Map(); - // map from name to recognizer - auxNames = new Map(); + // map from name to rule + auxRulesByName = new Map(); - // map from starting path to recognizer - auxRoutes = new Map(); + // map from starting path to rule + auxRulesByPath = new Map(); // TODO: optimize this into a trie - matchers: AbstractRecognizer[] = []; + rules: AbstractRule[] = []; - defaultRoute: RouteRecognizer = null; + // the rule to use automatically when recognizing or generating from this rule set + defaultRule: RouteRule = null; /** - * returns whether or not the config is terminal + * Configure additional rules in this rule set from a route definition + * @returns {boolean} true if the config is terminal */ config(config: RouteDefinition): boolean { - var handler; + let handler; if (isPresent(config.name) && config.name[0].toUpperCase() != config.name[0]) { - var suggestedName = config.name[0].toUpperCase() + config.name.substring(1); + 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}".`); } @@ -51,20 +53,20 @@ export class RuleSet { 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); + let auxRule = new RouteRule(config.path, handler); + this.auxRulesByPath.set(path, auxRule); if (isPresent(config.name)) { - this.auxNames.set(config.name, recognizer); + this.auxRulesByName.set(config.name, auxRule); } - return recognizer.terminal; + return auxRule.terminal; } - var useAsDefault = false; + let useAsDefault = false; if (config instanceof Redirect) { - let redirector = new RedirectRecognizer(config.path, config.redirectTo); + let redirector = new RedirectRule(config.path, config.redirectTo); this._assertNoHashCollision(redirector.hash, config.path); - this.matchers.push(redirector); + this.rules.push(redirector); return true; } @@ -75,27 +77,27 @@ export class RuleSet { handler = new AsyncRouteHandler(config.loader, config.data); useAsDefault = isPresent(config.useAsDefault) && config.useAsDefault; } - var recognizer = new RouteRecognizer(config.path, handler); + let newRule = new RouteRule(config.path, handler); - this._assertNoHashCollision(recognizer.hash, config.path); + this._assertNoHashCollision(newRule.hash, config.path); if (useAsDefault) { - if (isPresent(this.defaultRoute)) { + if (isPresent(this.defaultRule)) { throw new BaseException(`Only one route can be default`); } - this.defaultRoute = recognizer; + this.defaultRule = newRule; } - this.matchers.push(recognizer); + this.rules.push(newRule); if (isPresent(config.name)) { - this.names.set(config.name, recognizer); + this.rulesByName.set(config.name, newRule); } - return recognizer.terminal; + return newRule.terminal; } private _assertNoHashCollision(hash: string, path) { - this.matchers.forEach((matcher) => { + this.rules.forEach((matcher) => { if (hash == matcher.hash) { throw new BaseException( `Configuration '${path}' conflicts with existing route '${matcher.path}'`); @@ -110,7 +112,7 @@ export class RuleSet { recognize(urlParse: Url): Promise[] { var solutions = []; - this.matchers.forEach((routeRecognizer: AbstractRecognizer) => { + this.rules.forEach((routeRecognizer: AbstractRule) => { var pathMatch = routeRecognizer.recognize(urlParse); if (isPresent(pathMatch)) { @@ -127,7 +129,7 @@ export class RuleSet { } recognizeAuxiliary(urlParse: Url): Promise[] { - var routeRecognizer: RouteRecognizer = this.auxRoutes.get(urlParse.path); + var routeRecognizer: RouteRule = this.auxRulesByPath.get(urlParse.path); if (isPresent(routeRecognizer)) { return [routeRecognizer.recognize(urlParse)]; } @@ -135,18 +137,18 @@ export class RuleSet { return [PromiseWrapper.resolve(null)]; } - hasRoute(name: string): boolean { return this.names.has(name); } + hasRoute(name: string): boolean { return this.rulesByName.has(name); } componentLoaded(name: string): boolean { - return this.hasRoute(name) && isPresent(this.names.get(name).handler.componentType); + return this.hasRoute(name) && isPresent(this.rulesByName.get(name).handler.componentType); } loadComponent(name: string): Promise { - return this.names.get(name).handler.resolveComponentType(); + return this.rulesByName.get(name).handler.resolveComponentType(); } generate(name: string, params: any): ComponentInstruction { - var pathRecognizer: RouteRecognizer = this.names.get(name); + var pathRecognizer: RouteRule = this.rulesByName.get(name); if (isBlank(pathRecognizer)) { return null; } @@ -154,7 +156,7 @@ export class RuleSet { } generateAuxiliary(name: string, params: any): ComponentInstruction { - var pathRecognizer: RouteRecognizer = this.auxNames.get(name); + var pathRecognizer: RouteRule = this.auxRulesByName.get(name); if (isBlank(pathRecognizer)) { return null; } diff --git a/modules/angular2/src/router/route_recognizer.ts b/modules/angular2/src/router/rules.ts similarity index 92% rename from modules/angular2/src/router/route_recognizer.ts rename to modules/angular2/src/router/rules.ts index 1aa80a7590dd..ee4b8c69c1b6 100644 --- a/modules/angular2/src/router/route_recognizer.ts +++ b/modules/angular2/src/router/rules.ts @@ -9,16 +9,9 @@ import {ComponentInstruction} from './instruction'; import {PathRecognizer, GeneratedUrlSegment} from './path_recognizer'; +// RouteMatch objects hold information about a match between a rule and a URL export abstract class RouteMatch {} -export interface AbstractRecognizer { - hash: string; - path: string; - recognize(beginningSegment: Url): Promise; - generate(params: {[key: string]: any}): ComponentInstruction; -} - - export class PathMatch extends RouteMatch { constructor(public instruction: ComponentInstruction, public remaining: Url, public remainingAux: Url[]) { @@ -26,12 +19,19 @@ export class PathMatch extends RouteMatch { } } - export class RedirectMatch extends RouteMatch { constructor(public redirectTo: any[], public specificity) { super(); } } -export class RedirectRecognizer implements AbstractRecognizer { +// Rules are responsible for recognizing URL segments and generating instructions +export interface AbstractRule { + hash: string; + path: string; + recognize(beginningSegment: Url): Promise; + generate(params: {[key: string]: any}): ComponentInstruction; +} + +export class RedirectRule implements AbstractRule { private _pathRecognizer: PathRecognizer; public hash: string; @@ -58,7 +58,7 @@ export class RedirectRecognizer implements AbstractRecognizer { // represents something like '/foo/:bar' -export class RouteRecognizer implements AbstractRecognizer { +export class RouteRule implements AbstractRule { specificity: string; terminal: boolean = true; hash: string; diff --git a/modules/angular2/test/router/rule_set_spec.ts b/modules/angular2/test/router/rule_set_spec.ts index 5d6043aff733..b10d17ef3046 100644 --- a/modules/angular2/test/router/rule_set_spec.ts +++ b/modules/angular2/test/router/rule_set_spec.ts @@ -12,7 +12,7 @@ import { 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'; import {RuleSet} from 'angular2/src/router/rule_set'; import {Route, Redirect} from 'angular2/src/router/route_config_decorator'; From 27b334865dcc09b9b5a8b031d8ff746e6dd1a5fa Mon Sep 17 00:00:00 2001 From: Peter Bacon Darwin Date: Sun, 14 Feb 2016 17:50:39 +0000 Subject: [PATCH 08/43] refactor(router): DefaultInstruction can inherit from ResolvedInstruction --- modules/angular2/src/router/instruction.ts | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/modules/angular2/src/router/instruction.ts b/modules/angular2/src/router/instruction.ts index fe36a34eb161..02f4cd1a8c3e 100644 --- a/modules/angular2/src/router/instruction.ts +++ b/modules/angular2/src/router/instruction.ts @@ -224,15 +224,11 @@ export class ResolvedInstruction extends Instruction { /** * Represents a resolved default route */ -export class DefaultInstruction extends Instruction { +export class DefaultInstruction extends ResolvedInstruction { constructor(component: ComponentInstruction, child: DefaultInstruction) { super(component, child, {}); } - resolveComponent(): Promise { - return PromiseWrapper.resolve(this.component); - } - toLinkUrl(): string { return ''; } /** @internal */ @@ -292,8 +288,7 @@ export class RedirectInstruction extends ResolvedInstruction { /** - * A `ComponentInstruction` represents the route state for a single component. An `Instruction` is - * composed of a tree of these `ComponentInstruction`s. + * A `ComponentInstruction` represents the route state for a single component. * * `ComponentInstructions` is a public API. Instances of `ComponentInstruction` are passed * to route lifecycle hooks, like {@link CanActivate}. @@ -308,6 +303,9 @@ export class ComponentInstruction { reuse: boolean = false; public routeData: RouteData; + /** + * @internal + */ constructor(public urlPath: string, public urlParams: string[], data: RouteData, public componentType, public terminal: boolean, public specificity: string, public params: {[key: string]: any} = null) { From 8fb31f299599f3e0f437dcef451412f00f7a61d5 Mon Sep 17 00:00:00 2001 From: Peter Bacon Darwin Date: Sun, 14 Feb 2016 17:59:11 +0000 Subject: [PATCH 09/43] refactor(router): move route handlers into their own folder --- .../src/router/{ => route_handlers}/async_route_handler.ts | 2 +- .../angular2/src/router/{ => route_handlers}/route_handler.ts | 2 +- .../src/router/{ => route_handlers}/sync_route_handler.ts | 2 +- modules/angular2/src/router/rule_set.ts | 4 ++-- modules/angular2/src/router/rules.ts | 2 +- 5 files changed, 6 insertions(+), 6 deletions(-) rename modules/angular2/src/router/{ => route_handlers}/async_route_handler.ts (92%) rename modules/angular2/src/router/{ => route_handlers}/route_handler.ts (79%) rename modules/angular2/src/router/{ => route_handlers}/sync_route_handler.ts (91%) diff --git a/modules/angular2/src/router/async_route_handler.ts b/modules/angular2/src/router/route_handlers/async_route_handler.ts similarity index 92% rename from modules/angular2/src/router/async_route_handler.ts rename to modules/angular2/src/router/route_handlers/async_route_handler.ts index 62ea9b5b1221..44cf0d3001fb 100644 --- a/modules/angular2/src/router/async_route_handler.ts +++ b/modules/angular2/src/router/route_handlers/async_route_handler.ts @@ -1,7 +1,7 @@ import {isPresent, Type} from 'angular2/src/facade/lang'; import {RouteHandler} from './route_handler'; -import {RouteData, BLANK_ROUTE_DATA} from './instruction'; +import {RouteData, BLANK_ROUTE_DATA} from '../instruction'; export class AsyncRouteHandler implements RouteHandler { diff --git a/modules/angular2/src/router/route_handler.ts b/modules/angular2/src/router/route_handlers/route_handler.ts similarity index 79% rename from modules/angular2/src/router/route_handler.ts rename to modules/angular2/src/router/route_handlers/route_handler.ts index cb5f510378fc..d34ddad300fb 100644 --- a/modules/angular2/src/router/route_handler.ts +++ b/modules/angular2/src/router/route_handlers/route_handler.ts @@ -1,5 +1,5 @@ import {Type} from 'angular2/src/facade/lang'; -import {RouteData} from './instruction'; +import {RouteData} from '../instruction'; export interface RouteHandler { componentType: Type; diff --git a/modules/angular2/src/router/sync_route_handler.ts b/modules/angular2/src/router/route_handlers/sync_route_handler.ts similarity index 91% rename from modules/angular2/src/router/sync_route_handler.ts rename to modules/angular2/src/router/route_handlers/sync_route_handler.ts index c9c90fefd057..198933d3ce0b 100644 --- a/modules/angular2/src/router/sync_route_handler.ts +++ b/modules/angular2/src/router/route_handlers/sync_route_handler.ts @@ -2,7 +2,7 @@ import {PromiseWrapper} from 'angular2/src/facade/async'; import {isPresent, Type} from 'angular2/src/facade/lang'; import {RouteHandler} from './route_handler'; -import {RouteData, BLANK_ROUTE_DATA} from './instruction'; +import {RouteData, BLANK_ROUTE_DATA} from '../instruction'; export class SyncRouteHandler implements RouteHandler { diff --git a/modules/angular2/src/router/rule_set.ts b/modules/angular2/src/router/rule_set.ts index 47eacf5e9fe2..57c10d636768 100644 --- a/modules/angular2/src/router/rule_set.ts +++ b/modules/angular2/src/router/rule_set.ts @@ -11,8 +11,8 @@ import { PathMatch } from './rules'; import {Route, AsyncRoute, AuxRoute, Redirect, RouteDefinition} from './route_config_impl'; -import {AsyncRouteHandler} from './async_route_handler'; -import {SyncRouteHandler} from './sync_route_handler'; +import {AsyncRouteHandler} from './route_handlers/async_route_handler'; +import {SyncRouteHandler} from './route_handlers/sync_route_handler'; import {Url} from './url_parser'; import {ComponentInstruction} from './instruction'; diff --git a/modules/angular2/src/router/rules.ts b/modules/angular2/src/router/rules.ts index ee4b8c69c1b6..5d4292018b97 100644 --- a/modules/angular2/src/router/rules.ts +++ b/modules/angular2/src/router/rules.ts @@ -3,7 +3,7 @@ import {BaseException} from 'angular2/src/facade/exceptions'; import {PromiseWrapper} from 'angular2/src/facade/promise'; 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 {ComponentInstruction} from './instruction'; import {PathRecognizer, GeneratedUrlSegment} from './path_recognizer'; From 8a345767f3a2524a2fbdece821b044689884091f Mon Sep 17 00:00:00 2001 From: Peter Bacon Darwin Date: Sun, 14 Feb 2016 18:12:44 +0000 Subject: [PATCH 10/43] refactor(router): move location classes into location folder --- modules/angular2/platform/testing/browser_static.ts | 2 +- modules/angular2/platform/testing/server.ts | 2 +- modules/angular2/router.ts | 10 +++++----- modules/angular2/src/mock/location_mock.ts | 2 +- modules/angular2/src/mock/mock_location_strategy.ts | 2 +- modules/angular2/src/platform/worker_render_common.ts | 2 +- .../router/{ => location}/browser_platform_location.ts | 0 .../router/{ => location}/hash_location_strategy.ts | 0 modules/angular2/src/router/{ => location}/location.ts | 0 .../src/router/{ => location}/location_strategy.ts | 0 .../router/{ => location}/path_location_strategy.ts | 0 .../src/router/{ => location}/platform_location.ts | 0 modules/angular2/src/router/router.ts | 2 +- modules/angular2/src/router/router_link.ts | 2 +- modules/angular2/src/router/router_providers.ts | 4 ++-- modules/angular2/src/router/router_providers_common.ts | 6 +++--- .../angular2/src/web_workers/ui/platform_location.ts | 4 ++-- .../angular2/src/web_workers/ui/router_providers.ts | 2 +- .../src/web_workers/worker/platform_location.ts | 2 +- .../src/web_workers/worker/router_providers.ts | 2 +- .../test/router/hash_location_strategy_spec.ts | 6 +++--- modules/angular2/test/router/integration/util.ts | 2 +- modules/angular2/test/router/location_spec.ts | 4 ++-- .../test/router/path_location_strategy_spec.ts | 6 +++--- modules/angular2/test/router/route_config_spec.ts | 2 +- modules/angular2/test/router/router_spec.ts | 2 +- modules/playground/src/web_workers/router/index.ts | 2 +- 27 files changed, 34 insertions(+), 34 deletions(-) rename modules/angular2/src/router/{ => location}/browser_platform_location.ts (100%) rename modules/angular2/src/router/{ => location}/hash_location_strategy.ts (100%) rename modules/angular2/src/router/{ => location}/location.ts (100%) rename modules/angular2/src/router/{ => location}/location_strategy.ts (100%) rename modules/angular2/src/router/{ => location}/path_location_strategy.ts (100%) rename modules/angular2/src/router/{ => location}/platform_location.ts (100%) diff --git a/modules/angular2/platform/testing/browser_static.ts b/modules/angular2/platform/testing/browser_static.ts index 1f4192134e0e..d1555c719b17 100644 --- a/modules/angular2/platform/testing/browser_static.ts +++ b/modules/angular2/platform/testing/browser_static.ts @@ -15,7 +15,7 @@ import {MockAnimationBuilder} from 'angular2/src/mock/animation_builder_mock'; import {MockDirectiveResolver} from 'angular2/src/mock/directive_resolver_mock'; import {MockViewResolver} from 'angular2/src/mock/view_resolver_mock'; 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 {XHRImpl} from "angular2/src/platform/browser/xhr_impl"; diff --git a/modules/angular2/platform/testing/server.ts b/modules/angular2/platform/testing/server.ts index 47156c14d46c..a6bdb3c3b169 100644 --- a/modules/angular2/platform/testing/server.ts +++ b/modules/angular2/platform/testing/server.ts @@ -16,7 +16,7 @@ import {MockAnimationBuilder} from 'angular2/src/mock/animation_builder_mock'; import {MockDirectiveResolver} from 'angular2/src/mock/directive_resolver_mock'; import {MockViewResolver} from 'angular2/src/mock/view_resolver_mock'; 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 {TestComponentBuilder} from 'angular2/src/testing/test_component_builder'; diff --git a/modules/angular2/router.ts b/modules/angular2/router.ts index 7d028817f5e9..1faa59bdae6b 100644 --- a/modules/angular2/router.ts +++ b/modules/angular2/router.ts @@ -8,12 +8,12 @@ export {Router} from './src/router/router'; export {RouterOutlet} from './src/router/router_outlet'; export {RouterLink} from './src/router/router_link'; 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 {LocationStrategy, APP_BASE_HREF} from './src/router/location_strategy'; -export {HashLocationStrategy} from './src/router/hash_location_strategy'; -export {PathLocationStrategy} from './src/router/path_location_strategy'; -export {Location} from './src/router/location'; +export {LocationStrategy, APP_BASE_HREF} from './src/router/location/location_strategy'; +export {HashLocationStrategy} from './src/router/location/hash_location_strategy'; +export {PathLocationStrategy} from './src/router/location/path_location_strategy'; +export {Location} from './src/router/location/location'; export * from './src/router/route_config_decorator'; export * from './src/router/route_definition'; export {OnActivate, OnDeactivate, OnReuse, CanDeactivate, CanReuse} from './src/router/interfaces'; diff --git a/modules/angular2/src/mock/location_mock.ts b/modules/angular2/src/mock/location_mock.ts index 0c70727e46f5..759ab04c2b6e 100644 --- a/modules/angular2/src/mock/location_mock.ts +++ b/modules/angular2/src/mock/location_mock.ts @@ -1,7 +1,7 @@ import {Injectable} from 'angular2/src/core/di'; import {EventEmitter, ObservableWrapper} from 'angular2/src/facade/async'; 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. diff --git a/modules/angular2/src/mock/mock_location_strategy.ts b/modules/angular2/src/mock/mock_location_strategy.ts index de7dcb746d2d..9fa30767d08c 100644 --- a/modules/angular2/src/mock/mock_location_strategy.ts +++ b/modules/angular2/src/mock/mock_location_strategy.ts @@ -1,6 +1,6 @@ import {Injectable} from 'angular2/src/core/di'; 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'; /** diff --git a/modules/angular2/src/platform/worker_render_common.ts b/modules/angular2/src/platform/worker_render_common.ts index 9298081d4f2a..e1f4c7c6c29e 100644 --- a/modules/angular2/src/platform/worker_render_common.ts +++ b/modules/angular2/src/platform/worker_render_common.ts @@ -36,7 +36,7 @@ import {BrowserDomAdapter} from './browser/browser_adapter'; import {wtfInit} from 'angular2/src/core/profile/wtf_init'; import {MessageBasedRenderer} from 'angular2/src/web_workers/ui/renderer'; 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 { ServiceMessageBrokerFactory, ServiceMessageBrokerFactory_ diff --git a/modules/angular2/src/router/browser_platform_location.ts b/modules/angular2/src/router/location/browser_platform_location.ts similarity index 100% rename from modules/angular2/src/router/browser_platform_location.ts rename to modules/angular2/src/router/location/browser_platform_location.ts diff --git a/modules/angular2/src/router/hash_location_strategy.ts b/modules/angular2/src/router/location/hash_location_strategy.ts similarity index 100% rename from modules/angular2/src/router/hash_location_strategy.ts rename to modules/angular2/src/router/location/hash_location_strategy.ts diff --git a/modules/angular2/src/router/location.ts b/modules/angular2/src/router/location/location.ts similarity index 100% rename from modules/angular2/src/router/location.ts rename to modules/angular2/src/router/location/location.ts diff --git a/modules/angular2/src/router/location_strategy.ts b/modules/angular2/src/router/location/location_strategy.ts similarity index 100% rename from modules/angular2/src/router/location_strategy.ts rename to modules/angular2/src/router/location/location_strategy.ts diff --git a/modules/angular2/src/router/path_location_strategy.ts b/modules/angular2/src/router/location/path_location_strategy.ts similarity index 100% rename from modules/angular2/src/router/path_location_strategy.ts rename to modules/angular2/src/router/location/path_location_strategy.ts diff --git a/modules/angular2/src/router/platform_location.ts b/modules/angular2/src/router/location/platform_location.ts similarity index 100% rename from modules/angular2/src/router/platform_location.ts rename to modules/angular2/src/router/location/platform_location.ts diff --git a/modules/angular2/src/router/router.ts b/modules/angular2/src/router/router.ts index 97be56ce55c0..c56481e9b102 100644 --- a/modules/angular2/src/router/router.ts +++ b/modules/angular2/src/router/router.ts @@ -10,7 +10,7 @@ import { Instruction, } from './instruction'; import {RouterOutlet} from './router_outlet'; -import {Location} from './location'; +import {Location} from './location/location'; import {getCanActivateHook} from './route_lifecycle_reflector'; import {RouteDefinition} from './route_config_impl'; diff --git a/modules/angular2/src/router/router_link.ts b/modules/angular2/src/router/router_link.ts index bc51960bdee8..dc9d7f727fc5 100644 --- a/modules/angular2/src/router/router_link.ts +++ b/modules/angular2/src/router/router_link.ts @@ -2,7 +2,7 @@ import {Directive} from 'angular2/core'; import {isString} from 'angular2/src/facade/lang'; import {Router} from './router'; -import {Location} from './location'; +import {Location} from './location/location'; import {Instruction} from './instruction'; /** diff --git a/modules/angular2/src/router/router_providers.ts b/modules/angular2/src/router/router_providers.ts index 4b50f160798e..76ef8da2c120 100644 --- a/modules/angular2/src/router/router_providers.ts +++ b/modules/angular2/src/router/router_providers.ts @@ -2,8 +2,8 @@ import {ROUTER_PROVIDERS_COMMON} from 'angular2/router'; import {Provider} from 'angular2/core'; import {CONST_EXPR} from 'angular2/src/facade/lang'; -import {BrowserPlatformLocation} from './browser_platform_location'; -import {PlatformLocation} from './platform_location'; +import {BrowserPlatformLocation} from './location/browser_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. diff --git a/modules/angular2/src/router/router_providers_common.ts b/modules/angular2/src/router/router_providers_common.ts index 823634b133c1..f2c3a6582700 100644 --- a/modules/angular2/src/router/router_providers_common.ts +++ b/modules/angular2/src/router/router_providers_common.ts @@ -1,8 +1,8 @@ -import {LocationStrategy} from 'angular2/src/router/location_strategy'; -import {PathLocationStrategy} from 'angular2/src/router/path_location_strategy'; +import {LocationStrategy} from 'angular2/src/router/location/location_strategy'; +import {PathLocationStrategy} from 'angular2/src/router/location/path_location_strategy'; import {Router, RootRouter} from 'angular2/src/router/router'; 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 {ApplicationRef, OpaqueToken, Provider} from 'angular2/core'; import {BaseException} from 'angular2/src/facade/exceptions'; diff --git a/modules/angular2/src/web_workers/ui/platform_location.ts b/modules/angular2/src/web_workers/ui/platform_location.ts index 5bd3f6e5942b..fa9bd1c315f2 100644 --- a/modules/angular2/src/web_workers/ui/platform_location.ts +++ b/modules/angular2/src/web_workers/ui/platform_location.ts @@ -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 {ROUTER_CHANNEL} from 'angular2/src/web_workers/shared/messaging_api'; import { @@ -10,7 +10,7 @@ import {bind} from './bind'; import {LocationType} from 'angular2/src/web_workers/shared/serialized_types'; import {MessageBus} from 'angular2/src/web_workers/shared/message_bus'; 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() export class MessageBasedPlatformLocation { diff --git a/modules/angular2/src/web_workers/ui/router_providers.ts b/modules/angular2/src/web_workers/ui/router_providers.ts index 21805ee2e045..21edef9bebbd 100644 --- a/modules/angular2/src/web_workers/ui/router_providers.ts +++ b/modules/angular2/src/web_workers/ui/router_providers.ts @@ -1,6 +1,6 @@ import {MessageBasedPlatformLocation} from './platform_location'; 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'; export const WORKER_RENDER_ROUTER = CONST_EXPR([ diff --git a/modules/angular2/src/web_workers/worker/platform_location.ts b/modules/angular2/src/web_workers/worker/platform_location.ts index a4d5a0a3c3fd..59ce6bee845a 100644 --- a/modules/angular2/src/web_workers/worker/platform_location.ts +++ b/modules/angular2/src/web_workers/worker/platform_location.ts @@ -3,7 +3,7 @@ import { PlatformLocation, UrlChangeEvent, UrlChangeListener -} from 'angular2/src/router/platform_location'; +} from 'angular2/src/router/location/platform_location'; import { FnArg, UiArguments, diff --git a/modules/angular2/src/web_workers/worker/router_providers.ts b/modules/angular2/src/web_workers/worker/router_providers.ts index 193103fca83b..3a07f1cdd5c1 100644 --- a/modules/angular2/src/web_workers/worker/router_providers.ts +++ b/modules/angular2/src/web_workers/worker/router_providers.ts @@ -1,5 +1,5 @@ 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 {ROUTER_PROVIDERS_COMMON} from 'angular2/src/router/router_providers_common'; diff --git a/modules/angular2/test/router/hash_location_strategy_spec.ts b/modules/angular2/test/router/hash_location_strategy_spec.ts index e354cccfe086..0900de823a84 100644 --- a/modules/angular2/test/router/hash_location_strategy_spec.ts +++ b/modules/angular2/test/router/hash_location_strategy_spec.ts @@ -15,9 +15,9 @@ 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 {HashLocationStrategy} from 'angular2/src/router/hash_location_strategy'; +import {PlatformLocation} from 'angular2/src/router/location/platform_location'; +import {LocationStrategy, 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() { diff --git a/modules/angular2/test/router/integration/util.ts b/modules/angular2/test/router/integration/util.ts index 7789ebeb1a88..c0ee0e9f9a81 100644 --- a/modules/angular2/test/router/integration/util.ts +++ b/modules/angular2/test/router/integration/util.ts @@ -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'; diff --git a/modules/angular2/test/router/location_spec.ts b/modules/angular2/test/router/location_spec.ts index 5bd8e6ba1bc9..09e1296b9776 100644 --- a/modules/angular2/test/router/location_spec.ts +++ b/modules/angular2/test/router/location_spec.ts @@ -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() { diff --git a/modules/angular2/test/router/path_location_strategy_spec.ts b/modules/angular2/test/router/path_location_strategy_spec.ts index d1a88389c1a5..2ac63b23ad80 100644 --- a/modules/angular2/test/router/path_location_strategy_spec.ts +++ b/modules/angular2/test/router/path_location_strategy_spec.ts @@ -15,9 +15,9 @@ 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 {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() { diff --git a/modules/angular2/test/router/route_config_spec.ts b/modules/angular2/test/router/route_config_spec.ts index cfc97429b22f..a814408bef6a 100644 --- a/modules/angular2/test/router/route_config_spec.ts +++ b/modules/angular2/test/router/route_config_spec.ts @@ -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 { diff --git a/modules/angular2/test/router/router_spec.ts b/modules/angular2/test/router/router_spec.ts index d90a9727a00b..1f5ea7651fd7 100644 --- a/modules/angular2/test/router/router_spec.ts +++ b/modules/angular2/test/router/router_spec.ts @@ -18,7 +18,7 @@ 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'; diff --git a/modules/playground/src/web_workers/router/index.ts b/modules/playground/src/web_workers/router/index.ts index b9af0a442c1c..29f66f3ee49b 100644 --- a/modules/playground/src/web_workers/router/index.ts +++ b/modules/playground/src/web_workers/router/index.ts @@ -5,7 +5,7 @@ import { WORKER_SCRIPT, WORKER_RENDER_ROUTER } 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"; let ref = platform([WORKER_RENDER_PLATFORM]) From 8f984902c42885f3690d15ca71e331b366508b14 Mon Sep 17 00:00:00 2001 From: Peter Bacon Darwin Date: Mon, 15 Feb 2016 01:41:54 +0000 Subject: [PATCH 11/43] refactor(router): move rules into their own folder --- modules/angular2/src/router/route_registry.ts | 4 ++-- modules/angular2/src/router/{ => rules}/rule_set.ts | 10 +++++----- modules/angular2/src/router/{ => rules}/rules.ts | 8 ++++---- modules/angular2/test/router/rule_set_spec.ts | 4 ++-- 4 files changed, 13 insertions(+), 13 deletions(-) rename modules/angular2/src/router/{ => rules}/rule_set.ts (95%) rename modules/angular2/src/router/{ => rules}/rules.ts (94%) diff --git a/modules/angular2/src/router/route_registry.ts b/modules/angular2/src/router/route_registry.ts index a66b29046153..ab259c60b8c4 100644 --- a/modules/angular2/src/router/route_registry.ts +++ b/modules/angular2/src/router/route_registry.ts @@ -25,8 +25,8 @@ import { Redirect, RouteDefinition } from './route_config_impl'; -import {PathMatch, RedirectMatch, RouteMatch} from './rules'; -import {RuleSet} from './rule_set'; +import {PathMatch, RedirectMatch, RouteMatch} from './rules/rules'; +import {RuleSet} from './rules/rule_set'; import { Instruction, ResolvedInstruction, diff --git a/modules/angular2/src/router/rule_set.ts b/modules/angular2/src/router/rules/rule_set.ts similarity index 95% rename from modules/angular2/src/router/rule_set.ts rename to modules/angular2/src/router/rules/rule_set.ts index 57c10d636768..12c592fb7f86 100644 --- a/modules/angular2/src/router/rule_set.ts +++ b/modules/angular2/src/router/rules/rule_set.ts @@ -10,11 +10,11 @@ import { RouteMatch, PathMatch } from './rules'; -import {Route, AsyncRoute, AuxRoute, Redirect, RouteDefinition} from './route_config_impl'; -import {AsyncRouteHandler} from './route_handlers/async_route_handler'; -import {SyncRouteHandler} from './route_handlers/sync_route_handler'; -import {Url} from './url_parser'; -import {ComponentInstruction} from './instruction'; +import {Route, AsyncRoute, AuxRoute, Redirect, RouteDefinition} from '../route_config_impl'; +import {AsyncRouteHandler} from '../route_handlers/async_route_handler'; +import {SyncRouteHandler} from '../route_handlers/sync_route_handler'; +import {Url} from '../url_parser'; +import {ComponentInstruction} from '../instruction'; /** diff --git a/modules/angular2/src/router/rules.ts b/modules/angular2/src/router/rules/rules.ts similarity index 94% rename from modules/angular2/src/router/rules.ts rename to modules/angular2/src/router/rules/rules.ts index 5d4292018b97..6146f241a762 100644 --- a/modules/angular2/src/router/rules.ts +++ b/modules/angular2/src/router/rules/rules.ts @@ -3,10 +3,10 @@ import {BaseException} from 'angular2/src/facade/exceptions'; import {PromiseWrapper} from 'angular2/src/facade/promise'; import {Map} from 'angular2/src/facade/collection'; -import {RouteHandler} from './route_handlers/route_handler'; -import {Url} from './url_parser'; -import {ComponentInstruction} from './instruction'; -import {PathRecognizer, GeneratedUrlSegment} from './path_recognizer'; +import {RouteHandler} from '../route_handlers/route_handler'; +import {Url} from '../url_parser'; +import {ComponentInstruction} from '../instruction'; +import {PathRecognizer, GeneratedUrlSegment} from '../path_recognizer'; // RouteMatch objects hold information about a match between a rule and a URL diff --git a/modules/angular2/test/router/rule_set_spec.ts b/modules/angular2/test/router/rule_set_spec.ts index b10d17ef3046..3e28f6d5c53d 100644 --- a/modules/angular2/test/router/rule_set_spec.ts +++ b/modules/angular2/test/router/rule_set_spec.ts @@ -12,8 +12,8 @@ import { import {Map, StringMapWrapper} from 'angular2/src/facade/collection'; -import {RouteMatch, PathMatch, RedirectMatch} from 'angular2/src/router/rules'; -import {RuleSet} from 'angular2/src/router/rule_set'; +import {RouteMatch, PathMatch, RedirectMatch} from 'angular2/src/router/rules/rules'; +import {RuleSet} from 'angular2/src/router/rules/rule_set'; import {Route, Redirect} from 'angular2/src/router/route_config_decorator'; import {parser} from 'angular2/src/router/url_parser'; From 18c185774ef6300de0892860cb179bc5a4ebb67c Mon Sep 17 00:00:00 2001 From: Peter Bacon Darwin Date: Mon, 15 Feb 2016 02:09:02 +0000 Subject: [PATCH 12/43] refactor(router): move recognizers into their own folder --- .../{ => recognizers}/path_recognizer.ts | 141 ++++++------------ .../src/router/recognizers/recognizer.ts | 26 ++++ .../router/recognizers/regex_recognizer.ts | 36 +++++ modules/angular2/src/router/rules/rules.ts | 3 +- .../test/router/path_recognizer_spec.ts | 2 +- .../test/router/regex_recognizer_spec.ts | 3 +- 6 files changed, 111 insertions(+), 100 deletions(-) rename modules/angular2/src/router/{ => recognizers}/path_recognizer.ts (65%) create mode 100644 modules/angular2/src/router/recognizers/recognizer.ts create mode 100644 modules/angular2/src/router/recognizers/regex_recognizer.ts diff --git a/modules/angular2/src/router/path_recognizer.ts b/modules/angular2/src/router/recognizers/path_recognizer.ts similarity index 65% rename from modules/angular2/src/router/path_recognizer.ts rename to modules/angular2/src/router/recognizers/path_recognizer.ts index 89baf2961f1b..d823443e59ef 100644 --- a/modules/angular2/src/router/path_recognizer.ts +++ b/modules/angular2/src/router/recognizers/path_recognizer.ts @@ -9,7 +9,8 @@ import { import {BaseException, WrappedException} from 'angular2/src/facade/exceptions'; import {Map, MapWrapper, StringMapWrapper} from 'angular2/src/facade/collection'; -import {Url, RootUrl, serializeParams} from './url_parser'; +import {Url, RootUrl, serializeParams} from '../url_parser'; +import {GeneratedUrlSegment, RecognizedUrlSegment, Recognizer} from './recognizer'; class TouchMap { map: {[key: string]: string} = {}; @@ -45,26 +46,26 @@ function normalizeString(obj: any): string { } } -interface Segment { +interface PathSegment { name: string; generate(params: TouchMap): string; match(path: string): boolean; } -class ContinuationSegment implements Segment { +class ContinuationPathSegment implements PathSegment { name: string = ''; generate(params: TouchMap): string { return ''; } match(path: string): boolean { return true; } } -class StaticSegment implements Segment { +class StaticPathSegment implements PathSegment { 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 { +class DynamicPathSegment implements PathSegment { constructor(public name: string) {} match(path: string): boolean { return path.length > 0; } generate(params: TouchMap): string { @@ -77,15 +78,15 @@ class DynamicSegment implements Segment { } -class StarSegment implements Segment { +class StarPathSegment implements PathSegment { 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; +const paramMatcher = /^:([^\/]+)$/g; +const wildcardMatcher = /^\*([^\/]+)$/g; function parsePathString(route: string): {[key: string]: any} { // normalize route as not starting with a "/". Recognition will @@ -118,18 +119,18 @@ function parsePathString(route: string): {[key: string]: any} { var segment = segments[i], match; if (isPresent(match = RegExpWrapper.firstMatch(paramMatcher, segment))) { - results.push(new DynamicSegment(match[1])); + results.push(new DynamicPathSegment(match[1])); specificity += '1'; } else if (isPresent(match = RegExpWrapper.firstMatch(wildcardMatcher, segment))) { - results.push(new StarSegment(match[1])); + results.push(new StarPathSegment(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()); + results.push(new ContinuationPathSegment()); } else { - results.push(new StaticSegment(segment)); + results.push(new StaticPathSegment(segment)); specificity += '2'; } } @@ -139,15 +140,15 @@ function parsePathString(route: string): {[key: string]: any} { // this function is used to determine whether a route config path like `/foo/:id` collides with // `/foo/:name` -function pathDslHash(segments: Segment[]): string { +function pathDslHash(segments: PathSegment[]): string { return segments.map((segment) => { - if (segment instanceof StarSegment) { + if (segment instanceof StarPathSegment) { return '*'; - } else if (segment instanceof ContinuationSegment) { + } else if (segment instanceof ContinuationPathSegment) { return '...'; - } else if (segment instanceof DynamicSegment) { + } else if (segment instanceof DynamicPathSegment) { return ':'; - } else if (segment instanceof StaticSegment) { + } else if (segment instanceof StaticPathSegment) { return segment.path; } }) @@ -171,66 +172,12 @@ function assertPath(path: string) { } } -export class RecognizedUrlSegment { - constructor( - public urlPath: string, - public urlParams: string[], - public allParams: {[key: string]: string}, - public auxiliary: Url[], - public nextSegment: Url) {} -} - -export class GeneratedUrlSegment { - constructor(public urlPath: string, public urlParams: string[]) {} -} - -export interface Recognizer { - specificity: string; - terminal: boolean; - hash: string; - - recognize(beginningSegment: Url): RecognizedUrlSegment; - generate(params: {[key: string]: any}): GeneratedUrlSegment; -} - -export class RegexRecognizer implements Recognizer { - public hash: string; - public terminal: boolean = true; - public specificity: string = '2'; - private _regex: RegExp; - - constructor(private _reString: string, private _serializer: (params: {[key: string]: any}) => GeneratedUrlSegment) { - this.hash = this._reString; - this._regex = RegExpWrapper.create(this._reString); - } - - recognize(beginningSegment: Url): RecognizedUrlSegment { - var url = beginningSegment.toString(); - var match = RegExpWrapper.firstMatch(this._regex, url); - - if (isBlank(match)) { - return null; - } - - var params : {[key: string]: string} = {}; - - for (let i = 0; i < match.length; i += 1) { - params[i.toString()] = match[i]; - } - - return new RecognizedUrlSegment(url, [], params, [], null); - } - - generate(params: {[key: string]: any}): GeneratedUrlSegment { - return this._serializer(params); - } -} /** * Parses a URL string using a given matcher DSL, and generates URLs from param maps */ export class PathRecognizer implements Recognizer { - private _segments: Segment[]; + private _segments: PathSegment[]; specificity: string; terminal: boolean = true; hash: string; @@ -247,47 +194,47 @@ export class PathRecognizer implements Recognizer { this.hash = pathDslHash(this._segments); var lastSegment = this._segments[this._segments.length - 1]; - this.terminal = !(lastSegment instanceof ContinuationSegment); + this.terminal = !(lastSegment instanceof ContinuationPathSegment); } - recognize(beginningSegment: Url): RecognizedUrlSegment { - var nextSegment = beginningSegment; - var currentSegment: Url; + recognize(beginningUrlSegment: Url): RecognizedUrlSegment { + var nextUrlSegment = beginningUrlSegment; + var currentUrlSegment: Url; var positionalParams = {}; - var captured = []; + var captured : string[] = []; for (var i = 0; i < this._segments.length; i += 1) { - var segment = this._segments[i]; + var pathSegment = this._segments[i]; - currentSegment = nextSegment; - if (segment instanceof ContinuationSegment) { + currentUrlSegment = nextUrlSegment; + if (pathSegment instanceof ContinuationPathSegment) { break; } - if (isPresent(currentSegment)) { + if (isPresent(currentUrlSegment)) { // 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; + if (pathSegment instanceof StarPathSegment) { + positionalParams[pathSegment.name] = currentUrlSegment.toString(); + captured.push(currentUrlSegment.toString()); + nextUrlSegment = null; break; } - captured.push(currentSegment.path); + captured.push(currentUrlSegment.path); - if (segment instanceof DynamicSegment) { - positionalParams[segment.name] = currentSegment.path; - } else if (!segment.match(currentSegment.path)) { + if (pathSegment instanceof DynamicPathSegment) { + positionalParams[pathSegment.name] = currentUrlSegment.path; + } else if (!pathSegment.match(currentUrlSegment.path)) { return null; } - nextSegment = currentSegment.child; - } else if (!segment.match('')) { + nextUrlSegment = currentUrlSegment.child; + } else if (!pathSegment.match('')) { return null; } } - if (this.terminal && isPresent(nextSegment)) { + if (this.terminal && isPresent(nextUrlSegment)) { return null; } @@ -296,9 +243,9 @@ export class PathRecognizer implements Recognizer { var auxiliary; var urlParams; var allParams; - if (isPresent(currentSegment)) { + if (isPresent(currentUrlSegment)) { // If this is the root component, read query params. Otherwise, read matrix params. - var paramsSegment = beginningSegment instanceof RootUrl ? beginningSegment : currentSegment; + var paramsSegment = beginningUrlSegment instanceof RootUrl ? beginningUrlSegment : currentUrlSegment; allParams = isPresent(paramsSegment.params) ? StringMapWrapper.merge(paramsSegment.params, positionalParams) : @@ -307,14 +254,14 @@ export class PathRecognizer implements Recognizer { urlParams = serializeParams(paramsSegment.params); - auxiliary = currentSegment.auxiliary; + auxiliary = currentUrlSegment.auxiliary; } else { allParams = positionalParams; auxiliary = []; urlParams = []; } - return new RecognizedUrlSegment(urlPath, urlParams, allParams, auxiliary, nextSegment); + return new RecognizedUrlSegment(urlPath, urlParams, allParams, auxiliary, nextUrlSegment); } @@ -325,7 +272,7 @@ export class PathRecognizer implements Recognizer { for (var i = 0; i < this._segments.length; i++) { let segment = this._segments[i]; - if (!(segment instanceof ContinuationSegment)) { + if (!(segment instanceof ContinuationPathSegment)) { path.push(segment.generate(paramTokens)); } } diff --git a/modules/angular2/src/router/recognizers/recognizer.ts b/modules/angular2/src/router/recognizers/recognizer.ts new file mode 100644 index 000000000000..1a43558840bf --- /dev/null +++ b/modules/angular2/src/router/recognizers/recognizer.ts @@ -0,0 +1,26 @@ +import {Url} from '../url_parser'; + +export class RecognizedUrlSegment { + constructor( + public urlPath: string, + public urlParams: string[], + public allParams: {[key: string]: string}, + public auxiliary: Url[], + public nextSegment: Url) {} +} + + +export class GeneratedUrlSegment { + constructor(public urlPath: string, public urlParams: string[]) {} +} + + +export interface Recognizer { + specificity: string; + terminal: boolean; + hash: string; + + recognize(beginningSegment: Url): RecognizedUrlSegment; + generate(params: {[key: string]: any}): GeneratedUrlSegment; +} + diff --git a/modules/angular2/src/router/recognizers/regex_recognizer.ts b/modules/angular2/src/router/recognizers/regex_recognizer.ts new file mode 100644 index 000000000000..e785d8567e72 --- /dev/null +++ b/modules/angular2/src/router/recognizers/regex_recognizer.ts @@ -0,0 +1,36 @@ +import {RegExpWrapper, isBlank} from 'angular2/src/facade/lang'; +import {Url, RootUrl, serializeParams} from '../url_parser'; +import {GeneratedUrlSegment, RecognizedUrlSegment, Recognizer} from './recognizer'; + +export class RegexRecognizer implements Recognizer { + public hash: string; + public terminal: boolean = true; + public specificity: string = '2'; + private _regex: RegExp; + + constructor(private _reString: string, private _serializer: (params: {[key: string]: any}) => GeneratedUrlSegment) { + this.hash = this._reString; + this._regex = RegExpWrapper.create(this._reString); + } + + recognize(beginningSegment: Url): RecognizedUrlSegment { + var url = beginningSegment.toString(); + var match = RegExpWrapper.firstMatch(this._regex, url); + + if (isBlank(match)) { + return null; + } + + var params : {[key: string]: string} = {}; + + for (let i = 0; i < match.length; i += 1) { + params[i.toString()] = match[i]; + } + + return new RecognizedUrlSegment(url, [], params, [], null); + } + + generate(params: {[key: string]: any}): GeneratedUrlSegment { + return this._serializer(params); + } +} \ No newline at end of file diff --git a/modules/angular2/src/router/rules/rules.ts b/modules/angular2/src/router/rules/rules.ts index 6146f241a762..06b9aa873444 100644 --- a/modules/angular2/src/router/rules/rules.ts +++ b/modules/angular2/src/router/rules/rules.ts @@ -6,7 +6,8 @@ import {Map} from 'angular2/src/facade/collection'; import {RouteHandler} from '../route_handlers/route_handler'; import {Url} from '../url_parser'; import {ComponentInstruction} from '../instruction'; -import {PathRecognizer, GeneratedUrlSegment} from '../path_recognizer'; +import {PathRecognizer} from '../recognizers/path_recognizer'; +import {GeneratedUrlSegment} from '../recognizers/recognizer'; // RouteMatch objects hold information about a match between a rule and a URL diff --git a/modules/angular2/test/router/path_recognizer_spec.ts b/modules/angular2/test/router/path_recognizer_spec.ts index ec54d8af260e..b3d19999017d 100644 --- a/modules/angular2/test/router/path_recognizer_spec.ts +++ b/modules/angular2/test/router/path_recognizer_spec.ts @@ -10,7 +10,7 @@ import { SpyObject } from 'angular2/testing_internal'; -import {PathRecognizer} from 'angular2/src/router/path_recognizer'; +import {PathRecognizer} from 'angular2/src/router/recognizers/path_recognizer'; import {parser, Url} from 'angular2/src/router/url_parser'; export function main() { diff --git a/modules/angular2/test/router/regex_recognizer_spec.ts b/modules/angular2/test/router/regex_recognizer_spec.ts index 31c6981cfc38..3488243e4e51 100644 --- a/modules/angular2/test/router/regex_recognizer_spec.ts +++ b/modules/angular2/test/router/regex_recognizer_spec.ts @@ -10,7 +10,8 @@ import { SpyObject } from 'angular2/testing_internal'; -import {RegexRecognizer, GeneratedUrlSegment} from 'angular2/src/router/path_recognizer'; +import {GeneratedUrlSegment} from 'angular2/src/router/recognizers/recognizer'; +import {RegexRecognizer} from 'angular2/src/router/recognizers/regex_recognizer'; import {parser, Url} from 'angular2/src/router/url_parser'; export function main() { From c8898affc0dc19581ca3f4d4a29257de5b09a20a Mon Sep 17 00:00:00 2001 From: Peter Bacon Darwin Date: Mon, 15 Feb 2016 02:18:44 +0000 Subject: [PATCH 13/43] refactor(router): move lifecycle stuff into its own folder --- modules/angular2/router.ts | 2 +- .../src/router/{ => lifecycle}/lifecycle_annotations.dart | 0 .../src/router/{ => lifecycle}/lifecycle_annotations.ts | 2 +- .../src/router/{ => lifecycle}/lifecycle_annotations_impl.ts | 0 .../src/router/{ => lifecycle}/route_lifecycle_reflector.dart | 2 +- .../src/router/{ => lifecycle}/route_lifecycle_reflector.ts | 0 modules/angular2/src/router/router.ts | 2 +- modules/angular2/src/router/router_outlet.ts | 4 ++-- .../angular2/test/router/integration/lifecycle_hook_spec.ts | 2 +- 9 files changed, 7 insertions(+), 7 deletions(-) rename modules/angular2/src/router/{ => lifecycle}/lifecycle_annotations.dart (100%) rename modules/angular2/src/router/{ => lifecycle}/lifecycle_annotations.ts (97%) rename modules/angular2/src/router/{ => lifecycle}/lifecycle_annotations_impl.ts (100%) rename modules/angular2/src/router/{ => lifecycle}/route_lifecycle_reflector.dart (92%) rename modules/angular2/src/router/{ => lifecycle}/route_lifecycle_reflector.ts (100%) diff --git a/modules/angular2/router.ts b/modules/angular2/router.ts index 1faa59bdae6b..e489cf9cc54c 100644 --- a/modules/angular2/router.ts +++ b/modules/angular2/router.ts @@ -17,7 +17,7 @@ export {Location} from './src/router/location/location'; export * from './src/router/route_config_decorator'; export * from './src/router/route_definition'; 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 {OpaqueToken} from 'angular2/core'; export {ROUTER_PROVIDERS_COMMON} from 'angular2/src/router/router_providers_common'; diff --git a/modules/angular2/src/router/lifecycle_annotations.dart b/modules/angular2/src/router/lifecycle/lifecycle_annotations.dart similarity index 100% rename from modules/angular2/src/router/lifecycle_annotations.dart rename to modules/angular2/src/router/lifecycle/lifecycle_annotations.dart diff --git a/modules/angular2/src/router/lifecycle_annotations.ts b/modules/angular2/src/router/lifecycle/lifecycle_annotations.ts similarity index 97% rename from modules/angular2/src/router/lifecycle_annotations.ts rename to modules/angular2/src/router/lifecycle/lifecycle_annotations.ts index 895b027271f1..c94143c665eb 100644 --- a/modules/angular2/src/router/lifecycle_annotations.ts +++ b/modules/angular2/src/router/lifecycle/lifecycle_annotations.ts @@ -5,7 +5,7 @@ import {makeDecorator} from 'angular2/src/core/util/decorators'; import {CanActivate as CanActivateAnnotation} from './lifecycle_annotations_impl'; -import {ComponentInstruction} from './instruction'; +import {ComponentInstruction} from '../instruction'; export { routerCanReuse, diff --git a/modules/angular2/src/router/lifecycle_annotations_impl.ts b/modules/angular2/src/router/lifecycle/lifecycle_annotations_impl.ts similarity index 100% rename from modules/angular2/src/router/lifecycle_annotations_impl.ts rename to modules/angular2/src/router/lifecycle/lifecycle_annotations_impl.ts diff --git a/modules/angular2/src/router/route_lifecycle_reflector.dart b/modules/angular2/src/router/lifecycle/route_lifecycle_reflector.dart similarity index 92% rename from modules/angular2/src/router/route_lifecycle_reflector.dart rename to modules/angular2/src/router/lifecycle/route_lifecycle_reflector.dart index a8301aafc92c..99c576d19a34 100644 --- a/modules/angular2/src/router/route_lifecycle_reflector.dart +++ b/modules/angular2/src/router/lifecycle/route_lifecycle_reflector.dart @@ -1,6 +1,6 @@ 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/core/reflection/reflection.dart'; diff --git a/modules/angular2/src/router/route_lifecycle_reflector.ts b/modules/angular2/src/router/lifecycle/route_lifecycle_reflector.ts similarity index 100% rename from modules/angular2/src/router/route_lifecycle_reflector.ts rename to modules/angular2/src/router/lifecycle/route_lifecycle_reflector.ts diff --git a/modules/angular2/src/router/router.ts b/modules/angular2/src/router/router.ts index c56481e9b102..1fa25076d998 100644 --- a/modules/angular2/src/router/router.ts +++ b/modules/angular2/src/router/router.ts @@ -11,7 +11,7 @@ import { } from './instruction'; import {RouterOutlet} from './router_outlet'; import {Location} from './location/location'; -import {getCanActivateHook} from './route_lifecycle_reflector'; +import {getCanActivateHook} from './lifecycle/route_lifecycle_reflector'; import {RouteDefinition} from './route_config_impl'; let _resolveToTrue = PromiseWrapper.resolve(true); diff --git a/modules/angular2/src/router/router_outlet.ts b/modules/angular2/src/router/router_outlet.ts index 4abd36cffa26..3474b65429c4 100644 --- a/modules/angular2/src/router/router_outlet.ts +++ b/modules/angular2/src/router/router_outlet.ts @@ -16,8 +16,8 @@ import { import * as routerMod from './router'; import {ComponentInstruction, RouteParams, RouteData} from './instruction'; -import * as hookMod from './lifecycle_annotations'; -import {hasLifecycleHook} from './route_lifecycle_reflector'; +import * as hookMod from './lifecycle/lifecycle_annotations'; +import {hasLifecycleHook} from './lifecycle/route_lifecycle_reflector'; import {OnActivate, CanReuse, OnReuse, OnDeactivate, CanDeactivate} from './interfaces'; let _resolveToTrue = PromiseWrapper.resolve(true); diff --git a/modules/angular2/test/router/integration/lifecycle_hook_spec.ts b/modules/angular2/test/router/integration/lifecycle_hook_spec.ts index a644314d8572..9f9e8464e2d8 100644 --- a/modules/angular2/test/router/integration/lifecycle_hook_spec.ts +++ b/modules/angular2/test/router/integration/lifecycle_hook_spec.ts @@ -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'; From d94dc884d5f4004154db5bb1f12f058c98a9138c Mon Sep 17 00:00:00 2001 From: Peter Bacon Darwin Date: Mon, 15 Feb 2016 02:30:03 +0000 Subject: [PATCH 14/43] refactor(router): move route config stuff into its own folder --- modules/angular2/router.ts | 2 +- .../src/router/{ => route_config}/route_config_decorator.dart | 0 .../src/router/{ => route_config}/route_config_decorator.ts | 0 .../src/router/{ => route_config}/route_config_impl.ts | 4 ++-- .../src/router/{ => route_config}/route_config_nomalizer.dart | 0 .../src/router/{ => route_config}/route_config_nomalizer.ts | 4 ++-- modules/angular2/src/router/route_registry.ts | 4 ++-- modules/angular2/src/router/router.ts | 2 +- modules/angular2/src/router/rules/rule_set.ts | 2 +- modules/angular2/test/router/integration/bootstrap_spec.ts | 2 +- .../test/router/integration/impl/aux_route_spec_impl.ts | 2 +- .../angular2/test/router/integration/lifecycle_hook_spec.ts | 2 +- modules/angular2/test/router/integration/navigation_spec.ts | 2 +- .../angular2/test/router/integration/redirect_route_spec.ts | 2 +- modules/angular2/test/router/route_registry_spec.ts | 2 +- modules/angular2/test/router/router_spec.ts | 2 +- modules/angular2/test/router/rule_set_spec.ts | 2 +- 17 files changed, 17 insertions(+), 17 deletions(-) rename modules/angular2/src/router/{ => route_config}/route_config_decorator.dart (100%) rename modules/angular2/src/router/{ => route_config}/route_config_decorator.ts (100%) rename modules/angular2/src/router/{ => route_config}/route_config_impl.ts (98%) rename modules/angular2/src/router/{ => route_config}/route_config_nomalizer.dart (100%) rename modules/angular2/src/router/{ => route_config}/route_config_nomalizer.ts (97%) diff --git a/modules/angular2/router.ts b/modules/angular2/router.ts index e489cf9cc54c..b1f1399c2b69 100644 --- a/modules/angular2/router.ts +++ b/modules/angular2/router.ts @@ -14,7 +14,7 @@ export {LocationStrategy, APP_BASE_HREF} from './src/router/location/location_st export {HashLocationStrategy} from './src/router/location/hash_location_strategy'; export {PathLocationStrategy} from './src/router/location/path_location_strategy'; 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 {OnActivate, OnDeactivate, OnReuse, CanDeactivate, CanReuse} from './src/router/interfaces'; export {CanActivate} from './src/router/lifecycle/lifecycle_annotations'; diff --git a/modules/angular2/src/router/route_config_decorator.dart b/modules/angular2/src/router/route_config/route_config_decorator.dart similarity index 100% rename from modules/angular2/src/router/route_config_decorator.dart rename to modules/angular2/src/router/route_config/route_config_decorator.dart diff --git a/modules/angular2/src/router/route_config_decorator.ts b/modules/angular2/src/router/route_config/route_config_decorator.ts similarity index 100% rename from modules/angular2/src/router/route_config_decorator.ts rename to modules/angular2/src/router/route_config/route_config_decorator.ts diff --git a/modules/angular2/src/router/route_config_impl.ts b/modules/angular2/src/router/route_config/route_config_impl.ts similarity index 98% rename from modules/angular2/src/router/route_config_impl.ts rename to modules/angular2/src/router/route_config/route_config_impl.ts index 30be4f704a48..b766fd7a18d4 100644 --- a/modules/angular2/src/router/route_config_impl.ts +++ b/modules/angular2/src/router/route_config/route_config_impl.ts @@ -1,6 +1,6 @@ import {CONST, Type, isPresent} from 'angular2/src/facade/lang'; -import {RouteDefinition} from './route_definition'; -export {RouteDefinition} from './route_definition'; +import {RouteDefinition} from '../route_definition'; +export {RouteDefinition} from '../route_definition'; /** * The `RouteConfig` decorator defines routes for a given component. diff --git a/modules/angular2/src/router/route_config_nomalizer.dart b/modules/angular2/src/router/route_config/route_config_nomalizer.dart similarity index 100% rename from modules/angular2/src/router/route_config_nomalizer.dart rename to modules/angular2/src/router/route_config/route_config_nomalizer.dart diff --git a/modules/angular2/src/router/route_config_nomalizer.ts b/modules/angular2/src/router/route_config/route_config_nomalizer.ts similarity index 97% rename from modules/angular2/src/router/route_config_nomalizer.ts rename to modules/angular2/src/router/route_config/route_config_nomalizer.ts index cd666e6b3549..edadae4bd00a 100644 --- a/modules/angular2/src/router/route_config_nomalizer.ts +++ b/modules/angular2/src/router/route_config/route_config_nomalizer.ts @@ -1,8 +1,8 @@ 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 {BaseException, WrappedException} from 'angular2/src/facade/exceptions'; -import {RouteRegistry} from './route_registry'; +import {RouteRegistry} from '../route_registry'; /** diff --git a/modules/angular2/src/router/route_registry.ts b/modules/angular2/src/router/route_registry.ts index ab259c60b8c4..5ecec412a0a2 100644 --- a/modules/angular2/src/router/route_registry.ts +++ b/modules/angular2/src/router/route_registry.ts @@ -24,7 +24,7 @@ import { AuxRoute, Redirect, RouteDefinition -} from './route_config_impl'; +} from './route_config/route_config_impl'; import {PathMatch, RedirectMatch, RouteMatch} from './rules/rules'; import {RuleSet} from './rules/rule_set'; import { @@ -35,7 +35,7 @@ import { DefaultInstruction } from './instruction'; -import {normalizeRouteConfig, assertComponentExists} from './route_config_nomalizer'; +import {normalizeRouteConfig, assertComponentExists} from './route_config/route_config_nomalizer'; import {parser, Url, pathSegmentsToUrl} from './url_parser'; var _resolveToNull = PromiseWrapper.resolve(null); diff --git a/modules/angular2/src/router/router.ts b/modules/angular2/src/router/router.ts index 1fa25076d998..e762fa38028a 100644 --- a/modules/angular2/src/router/router.ts +++ b/modules/angular2/src/router/router.ts @@ -12,7 +12,7 @@ import { import {RouterOutlet} from './router_outlet'; import {Location} from './location/location'; 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 _resolveToFalse = PromiseWrapper.resolve(false); diff --git a/modules/angular2/src/router/rules/rule_set.ts b/modules/angular2/src/router/rules/rule_set.ts index 12c592fb7f86..892585d9f883 100644 --- a/modules/angular2/src/router/rules/rule_set.ts +++ b/modules/angular2/src/router/rules/rule_set.ts @@ -10,7 +10,7 @@ import { RouteMatch, PathMatch } from './rules'; -import {Route, AsyncRoute, AuxRoute, Redirect, RouteDefinition} from '../route_config_impl'; +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 {Url} from '../url_parser'; diff --git a/modules/angular2/test/router/integration/bootstrap_spec.ts b/modules/angular2/test/router/integration/bootstrap_spec.ts index 9518524947bd..08595f3b49f8 100644 --- a/modules/angular2/test/router/integration/bootstrap_spec.ts +++ b/modules/angular2/test/router/integration/bootstrap_spec.ts @@ -20,7 +20,7 @@ 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 { diff --git a/modules/angular2/test/router/integration/impl/aux_route_spec_impl.ts b/modules/angular2/test/router/integration/impl/aux_route_spec_impl.ts index 2f28f10ea86b..3fcb7368ad2a 100644 --- a/modules/angular2/test/router/integration/impl/aux_route_spec_impl.ts +++ b/modules/angular2/test/router/integration/impl/aux_route_spec_impl.ts @@ -19,7 +19,7 @@ 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'; diff --git a/modules/angular2/test/router/integration/lifecycle_hook_spec.ts b/modules/angular2/test/router/integration/lifecycle_hook_spec.ts index 9f9e8464e2d8..94a4ee247b5d 100644 --- a/modules/angular2/test/router/integration/lifecycle_hook_spec.ts +++ b/modules/angular2/test/router/integration/lifecycle_hook_spec.ts @@ -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, diff --git a/modules/angular2/test/router/integration/navigation_spec.ts b/modules/angular2/test/router/integration/navigation_spec.ts index 959f4794e5be..ea4230c53a18 100644 --- a/modules/angular2/test/router/integration/navigation_spec.ts +++ b/modules/angular2/test/router/integration/navigation_spec.ts @@ -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'; diff --git a/modules/angular2/test/router/integration/redirect_route_spec.ts b/modules/angular2/test/router/integration/redirect_route_spec.ts index 963fc78e3067..84fd398eeeca 100644 --- a/modules/angular2/test/router/integration/redirect_route_spec.ts +++ b/modules/angular2/test/router/integration/redirect_route_spec.ts @@ -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'; diff --git a/modules/angular2/test/router/route_registry_spec.ts b/modules/angular2/test/router/route_registry_spec.ts index 76385dbb735b..d0f1808f6e62 100644 --- a/modules/angular2/test/router/route_registry_spec.ts +++ b/modules/angular2/test/router/route_registry_spec.ts @@ -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() { diff --git a/modules/angular2/test/router/router_spec.ts b/modules/angular2/test/router/router_spec.ts index 1f5ea7651fd7..abf4f75edd46 100644 --- a/modules/angular2/test/router/router_spec.ts +++ b/modules/angular2/test/router/router_spec.ts @@ -21,7 +21,7 @@ import {SpyLocation} from 'angular2/src/mock/location_mock'; 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'; diff --git a/modules/angular2/test/router/rule_set_spec.ts b/modules/angular2/test/router/rule_set_spec.ts index 3e28f6d5c53d..c1106d266e04 100644 --- a/modules/angular2/test/router/rule_set_spec.ts +++ b/modules/angular2/test/router/rule_set_spec.ts @@ -15,7 +15,7 @@ import {Map, StringMapWrapper} from 'angular2/src/facade/collection'; import {RouteMatch, PathMatch, RedirectMatch} from 'angular2/src/router/rules/rules'; import {RuleSet} from 'angular2/src/router/rules/rule_set'; -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'; From 4039b8fc10b7d27a9e692b1e1797a944795ac8c4 Mon Sep 17 00:00:00 2001 From: Peter Bacon Darwin Date: Mon, 15 Feb 2016 02:49:25 +0000 Subject: [PATCH 15/43] refactor(router): move recognizers into the rules folder --- .../src/router/{recognizers => rules}/path_recognizer.ts | 0 .../angular2/src/router/{recognizers => rules}/recognizer.ts | 0 .../src/router/{recognizers => rules}/regex_recognizer.ts | 0 modules/angular2/src/router/rules/rules.ts | 4 ++-- modules/angular2/test/router/path_recognizer_spec.ts | 2 +- modules/angular2/test/router/regex_recognizer_spec.ts | 4 ++-- 6 files changed, 5 insertions(+), 5 deletions(-) rename modules/angular2/src/router/{recognizers => rules}/path_recognizer.ts (100%) rename modules/angular2/src/router/{recognizers => rules}/recognizer.ts (100%) rename modules/angular2/src/router/{recognizers => rules}/regex_recognizer.ts (100%) diff --git a/modules/angular2/src/router/recognizers/path_recognizer.ts b/modules/angular2/src/router/rules/path_recognizer.ts similarity index 100% rename from modules/angular2/src/router/recognizers/path_recognizer.ts rename to modules/angular2/src/router/rules/path_recognizer.ts diff --git a/modules/angular2/src/router/recognizers/recognizer.ts b/modules/angular2/src/router/rules/recognizer.ts similarity index 100% rename from modules/angular2/src/router/recognizers/recognizer.ts rename to modules/angular2/src/router/rules/recognizer.ts diff --git a/modules/angular2/src/router/recognizers/regex_recognizer.ts b/modules/angular2/src/router/rules/regex_recognizer.ts similarity index 100% rename from modules/angular2/src/router/recognizers/regex_recognizer.ts rename to modules/angular2/src/router/rules/regex_recognizer.ts diff --git a/modules/angular2/src/router/rules/rules.ts b/modules/angular2/src/router/rules/rules.ts index 06b9aa873444..d391ab654195 100644 --- a/modules/angular2/src/router/rules/rules.ts +++ b/modules/angular2/src/router/rules/rules.ts @@ -6,8 +6,8 @@ import {Map} from 'angular2/src/facade/collection'; import {RouteHandler} from '../route_handlers/route_handler'; import {Url} from '../url_parser'; import {ComponentInstruction} from '../instruction'; -import {PathRecognizer} from '../recognizers/path_recognizer'; -import {GeneratedUrlSegment} from '../recognizers/recognizer'; +import {PathRecognizer} from './path_recognizer'; +import {GeneratedUrlSegment} from './recognizer'; // RouteMatch objects hold information about a match between a rule and a URL diff --git a/modules/angular2/test/router/path_recognizer_spec.ts b/modules/angular2/test/router/path_recognizer_spec.ts index b3d19999017d..7a379a1bc0fb 100644 --- a/modules/angular2/test/router/path_recognizer_spec.ts +++ b/modules/angular2/test/router/path_recognizer_spec.ts @@ -10,7 +10,7 @@ import { SpyObject } from 'angular2/testing_internal'; -import {PathRecognizer} from 'angular2/src/router/recognizers/path_recognizer'; +import {PathRecognizer} from 'angular2/src/router/rules/path_recognizer'; import {parser, Url} from 'angular2/src/router/url_parser'; export function main() { diff --git a/modules/angular2/test/router/regex_recognizer_spec.ts b/modules/angular2/test/router/regex_recognizer_spec.ts index 3488243e4e51..99ce13353daa 100644 --- a/modules/angular2/test/router/regex_recognizer_spec.ts +++ b/modules/angular2/test/router/regex_recognizer_spec.ts @@ -10,8 +10,8 @@ import { SpyObject } from 'angular2/testing_internal'; -import {GeneratedUrlSegment} from 'angular2/src/router/recognizers/recognizer'; -import {RegexRecognizer} from 'angular2/src/router/recognizers/regex_recognizer'; +import {GeneratedUrlSegment} from 'angular2/src/router/rules/recognizer'; +import {RegexRecognizer} from 'angular2/src/router/rules/regex_recognizer'; import {parser, Url} from 'angular2/src/router/url_parser'; export function main() { From 785df6120fae23caf302e0dca49232613d8278ef Mon Sep 17 00:00:00 2001 From: Peter Bacon Darwin Date: Mon, 15 Feb 2016 02:56:28 +0000 Subject: [PATCH 16/43] refactor(router): move directives into their own folder --- modules/angular2/router.ts | 8 ++++---- modules/angular2/router/router_link_dsl.ts | 4 ++-- .../src/router/{ => directives}/router_link.ts | 6 +++--- .../router/{ => directives}/router_link_transform.ts | 0 .../src/router/{ => directives}/router_outlet.ts | 10 +++++----- modules/angular2/src/router/router.ts | 2 +- .../test/router/integration/router_link_spec.ts | 2 +- .../angular2/test/router/router_link_transform_spec.ts | 2 +- 8 files changed, 17 insertions(+), 17 deletions(-) rename modules/angular2/src/router/{ => directives}/router_link.ts (95%) rename modules/angular2/src/router/{ => directives}/router_link_transform.ts (100%) rename modules/angular2/src/router/{ => directives}/router_outlet.ts (95%) diff --git a/modules/angular2/router.ts b/modules/angular2/router.ts index b1f1399c2b69..245c2cb0724b 100644 --- a/modules/angular2/router.ts +++ b/modules/angular2/router.ts @@ -5,8 +5,8 @@ */ export {Router} from './src/router/router'; -export {RouterOutlet} from './src/router/router_outlet'; -export {RouterLink} from './src/router/router_link'; +export {RouterOutlet} from './src/router/directives/router_outlet'; +export {RouterLink} from './src/router/directives/router_link'; export {RouteParams, RouteData} from './src/router/instruction'; export {PlatformLocation} from './src/router/location/platform_location'; export {RouteRegistry, ROUTER_PRIMARY_COMPONENT} from './src/router/route_registry'; @@ -23,8 +23,8 @@ export {OpaqueToken} from 'angular2/core'; export {ROUTER_PROVIDERS_COMMON} from 'angular2/src/router/router_providers_common'; export {ROUTER_PROVIDERS, ROUTER_BINDINGS} from 'angular2/src/router/router_providers'; -import {RouterOutlet} from './src/router/router_outlet'; -import {RouterLink} from './src/router/router_link'; +import {RouterOutlet} from './src/router/directives/router_outlet'; +import {RouterLink} from './src/router/directives/router_link'; import {CONST_EXPR} from './src/facade/lang'; /** diff --git a/modules/angular2/router/router_link_dsl.ts b/modules/angular2/router/router_link_dsl.ts index 5f108b826f68..cfc1697882cb 100644 --- a/modules/angular2/router/router_link_dsl.ts +++ b/modules/angular2/router/router_link_dsl.ts @@ -1,9 +1,9 @@ import {TEMPLATE_TRANSFORMS} from 'angular2/compiler'; 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'; -export {RouterLinkTransform} from 'angular2/src/router/router_link_transform'; +export {RouterLinkTransform} from 'angular2/src/router/directives/router_link_transform'; /** * Enables the router link DSL. diff --git a/modules/angular2/src/router/router_link.ts b/modules/angular2/src/router/directives/router_link.ts similarity index 95% rename from modules/angular2/src/router/router_link.ts rename to modules/angular2/src/router/directives/router_link.ts index dc9d7f727fc5..45e288fa189d 100644 --- a/modules/angular2/src/router/router_link.ts +++ b/modules/angular2/src/router/directives/router_link.ts @@ -1,9 +1,9 @@ import {Directive} from 'angular2/core'; import {isString} from 'angular2/src/facade/lang'; -import {Router} from './router'; -import {Location} from './location/location'; -import {Instruction} from './instruction'; +import {Router} from '../router'; +import {Location} from '../location/location'; +import {Instruction} from '../instruction'; /** * The RouterLink directive lets you link to specific parts of your app. diff --git a/modules/angular2/src/router/router_link_transform.ts b/modules/angular2/src/router/directives/router_link_transform.ts similarity index 100% rename from modules/angular2/src/router/router_link_transform.ts rename to modules/angular2/src/router/directives/router_link_transform.ts diff --git a/modules/angular2/src/router/router_outlet.ts b/modules/angular2/src/router/directives/router_outlet.ts similarity index 95% rename from modules/angular2/src/router/router_outlet.ts rename to modules/angular2/src/router/directives/router_outlet.ts index 3474b65429c4..500d1d04b712 100644 --- a/modules/angular2/src/router/router_outlet.ts +++ b/modules/angular2/src/router/directives/router_outlet.ts @@ -14,11 +14,11 @@ import { Dependency } from 'angular2/core'; -import * as routerMod from './router'; -import {ComponentInstruction, RouteParams, RouteData} from './instruction'; -import * as hookMod from './lifecycle/lifecycle_annotations'; -import {hasLifecycleHook} from './lifecycle/route_lifecycle_reflector'; -import {OnActivate, CanReuse, OnReuse, OnDeactivate, CanDeactivate} from './interfaces'; +import * as routerMod from '../router'; +import {ComponentInstruction, RouteParams, RouteData} from '../instruction'; +import * as hookMod from '../lifecycle/lifecycle_annotations'; +import {hasLifecycleHook} from '../lifecycle/route_lifecycle_reflector'; +import {OnActivate, CanReuse, OnReuse, OnDeactivate, CanDeactivate} from '../interfaces'; let _resolveToTrue = PromiseWrapper.resolve(true); diff --git a/modules/angular2/src/router/router.ts b/modules/angular2/src/router/router.ts index e762fa38028a..6fbc00402373 100644 --- a/modules/angular2/src/router/router.ts +++ b/modules/angular2/src/router/router.ts @@ -9,7 +9,7 @@ import { ComponentInstruction, Instruction, } from './instruction'; -import {RouterOutlet} from './router_outlet'; +import {RouterOutlet} from './directives/router_outlet'; import {Location} from './location/location'; import {getCanActivateHook} from './lifecycle/route_lifecycle_reflector'; import {RouteDefinition} from './route_config/route_config_impl'; diff --git a/modules/angular2/test/router/integration/router_link_spec.ts b/modules/angular2/test/router/integration/router_link_spec.ts index f36b087e11de..306709537e3f 100644 --- a/modules/angular2/test/router/integration/router_link_spec.ts +++ b/modules/angular2/test/router/integration/router_link_spec.ts @@ -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() { diff --git a/modules/angular2/test/router/router_link_transform_spec.ts b/modules/angular2/test/router/router_link_transform_spec.ts index cc154ccf3c8b..7cb81dd99f1f 100644 --- a/modules/angular2/test/router/router_link_transform_spec.ts +++ b/modules/angular2/test/router/router_link_transform_spec.ts @@ -15,7 +15,7 @@ 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 {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'; From e523f7b245e1271496af3e97fa44ab1f53588f7b Mon Sep 17 00:00:00 2001 From: Peter Bacon Darwin Date: Mon, 15 Feb 2016 03:12:00 +0000 Subject: [PATCH 17/43] refactor(router): move urlParser into the rules folder --- modules/angular2/src/router/route_registry.ts | 2 +- modules/angular2/src/router/rules/path_recognizer.ts | 2 +- modules/angular2/src/router/rules/recognizer.ts | 2 +- modules/angular2/src/router/rules/regex_recognizer.ts | 2 +- modules/angular2/src/router/rules/rule_set.ts | 2 +- modules/angular2/src/router/rules/rules.ts | 2 +- modules/angular2/src/router/{ => rules}/url_parser.ts | 0 modules/angular2/test/router/path_recognizer_spec.ts | 2 +- modules/angular2/test/router/regex_recognizer_spec.ts | 2 +- modules/angular2/test/router/rule_set_spec.ts | 2 +- modules/angular2/test/router/url_parser_spec.ts | 2 +- 11 files changed, 10 insertions(+), 10 deletions(-) rename modules/angular2/src/router/{ => rules}/url_parser.ts (100%) diff --git a/modules/angular2/src/router/route_registry.ts b/modules/angular2/src/router/route_registry.ts index 5ecec412a0a2..8144a41aeb39 100644 --- a/modules/angular2/src/router/route_registry.ts +++ b/modules/angular2/src/router/route_registry.ts @@ -36,7 +36,7 @@ import { } from './instruction'; import {normalizeRouteConfig, assertComponentExists} from './route_config/route_config_nomalizer'; -import {parser, Url, pathSegmentsToUrl} from './url_parser'; +import {parser, Url, pathSegmentsToUrl} from './rules/url_parser'; var _resolveToNull = PromiseWrapper.resolve(null); diff --git a/modules/angular2/src/router/rules/path_recognizer.ts b/modules/angular2/src/router/rules/path_recognizer.ts index d823443e59ef..b1f77cd4b255 100644 --- a/modules/angular2/src/router/rules/path_recognizer.ts +++ b/modules/angular2/src/router/rules/path_recognizer.ts @@ -9,7 +9,7 @@ import { import {BaseException, WrappedException} from 'angular2/src/facade/exceptions'; import {Map, MapWrapper, StringMapWrapper} from 'angular2/src/facade/collection'; -import {Url, RootUrl, serializeParams} from '../url_parser'; +import {Url, RootUrl, serializeParams} from './url_parser'; import {GeneratedUrlSegment, RecognizedUrlSegment, Recognizer} from './recognizer'; class TouchMap { diff --git a/modules/angular2/src/router/rules/recognizer.ts b/modules/angular2/src/router/rules/recognizer.ts index 1a43558840bf..c2aa03ba94dc 100644 --- a/modules/angular2/src/router/rules/recognizer.ts +++ b/modules/angular2/src/router/rules/recognizer.ts @@ -1,4 +1,4 @@ -import {Url} from '../url_parser'; +import {Url} from './url_parser'; export class RecognizedUrlSegment { constructor( diff --git a/modules/angular2/src/router/rules/regex_recognizer.ts b/modules/angular2/src/router/rules/regex_recognizer.ts index e785d8567e72..916eee217900 100644 --- a/modules/angular2/src/router/rules/regex_recognizer.ts +++ b/modules/angular2/src/router/rules/regex_recognizer.ts @@ -1,5 +1,5 @@ import {RegExpWrapper, isBlank} from 'angular2/src/facade/lang'; -import {Url, RootUrl, serializeParams} from '../url_parser'; +import {Url, RootUrl, serializeParams} from './url_parser'; import {GeneratedUrlSegment, RecognizedUrlSegment, Recognizer} from './recognizer'; export class RegexRecognizer implements Recognizer { diff --git a/modules/angular2/src/router/rules/rule_set.ts b/modules/angular2/src/router/rules/rule_set.ts index 892585d9f883..ca23ad1eb27f 100644 --- a/modules/angular2/src/router/rules/rule_set.ts +++ b/modules/angular2/src/router/rules/rule_set.ts @@ -13,7 +13,7 @@ import { 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 {Url} from '../url_parser'; +import {Url} from './url_parser'; import {ComponentInstruction} from '../instruction'; diff --git a/modules/angular2/src/router/rules/rules.ts b/modules/angular2/src/router/rules/rules.ts index d391ab654195..0a9c0a0c21ad 100644 --- a/modules/angular2/src/router/rules/rules.ts +++ b/modules/angular2/src/router/rules/rules.ts @@ -4,7 +4,7 @@ import {PromiseWrapper} from 'angular2/src/facade/promise'; import {Map} from 'angular2/src/facade/collection'; import {RouteHandler} from '../route_handlers/route_handler'; -import {Url} from '../url_parser'; +import {Url} from './url_parser'; import {ComponentInstruction} from '../instruction'; import {PathRecognizer} from './path_recognizer'; import {GeneratedUrlSegment} from './recognizer'; diff --git a/modules/angular2/src/router/url_parser.ts b/modules/angular2/src/router/rules/url_parser.ts similarity index 100% rename from modules/angular2/src/router/url_parser.ts rename to modules/angular2/src/router/rules/url_parser.ts diff --git a/modules/angular2/test/router/path_recognizer_spec.ts b/modules/angular2/test/router/path_recognizer_spec.ts index 7a379a1bc0fb..a3900cf6487d 100644 --- a/modules/angular2/test/router/path_recognizer_spec.ts +++ b/modules/angular2/test/router/path_recognizer_spec.ts @@ -11,7 +11,7 @@ import { } from 'angular2/testing_internal'; import {PathRecognizer} from 'angular2/src/router/rules/path_recognizer'; -import {parser, Url} from 'angular2/src/router/url_parser'; +import {parser, Url} from 'angular2/src/router/rules/url_parser'; export function main() { describe('PathRecognizer', () => { diff --git a/modules/angular2/test/router/regex_recognizer_spec.ts b/modules/angular2/test/router/regex_recognizer_spec.ts index 99ce13353daa..8db41dd228ba 100644 --- a/modules/angular2/test/router/regex_recognizer_spec.ts +++ b/modules/angular2/test/router/regex_recognizer_spec.ts @@ -12,7 +12,7 @@ import { import {GeneratedUrlSegment} from 'angular2/src/router/rules/recognizer'; import {RegexRecognizer} from 'angular2/src/router/rules/regex_recognizer'; -import {parser, Url} from 'angular2/src/router/url_parser'; +import {parser, Url} from 'angular2/src/router/rules/url_parser'; export function main() { describe('RegexRecognizer', () => { diff --git a/modules/angular2/test/router/rule_set_spec.ts b/modules/angular2/test/router/rule_set_spec.ts index c1106d266e04..329e71387d83 100644 --- a/modules/angular2/test/router/rule_set_spec.ts +++ b/modules/angular2/test/router/rule_set_spec.ts @@ -16,7 +16,7 @@ import {RouteMatch, PathMatch, RedirectMatch} from 'angular2/src/router/rules/ru import {RuleSet} from 'angular2/src/router/rules/rule_set'; 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/rules/url_parser'; import {PromiseWrapper} from 'angular2/src/facade/promise'; diff --git a/modules/angular2/test/router/url_parser_spec.ts b/modules/angular2/test/router/url_parser_spec.ts index 12fd02c25ce6..96c30ee21e64 100644 --- a/modules/angular2/test/router/url_parser_spec.ts +++ b/modules/angular2/test/router/url_parser_spec.ts @@ -10,7 +10,7 @@ import { SpyObject } from 'angular2/testing_internal'; -import {UrlParser, Url} from 'angular2/src/router/url_parser'; +import {UrlParser, Url} from 'angular2/src/router/rules/url_parser'; export function main() { From 76922f8f8bd859876bf535d3388da8edfe648a45 Mon Sep 17 00:00:00 2001 From: Peter Bacon Darwin Date: Wed, 17 Feb 2016 11:39:57 +0000 Subject: [PATCH 18/43] refactor(router): change `Recognizer`s -> `PathRoute` and associated changes --- modules/angular2/src/router/route_registry.ts | 6 +- .../src/router/rules/param_route_path.ts | 276 +++++++++++++++++ .../src/router/rules/path_recognizer.ts | 286 ------------------ .../angular2/src/router/rules/recognizer.ts | 26 -- .../src/router/rules/regex_recognizer.ts | 36 --- .../src/router/rules/regex_route_path.ts | 44 +++ .../angular2/src/router/rules/route_path.ts | 30 ++ modules/angular2/src/router/rules/rules.ts | 35 +-- modules/angular2/src/router/utils.ts | 37 +++ ...nizer_spec.ts => param_route_path_spec.ts} | 48 +-- ...izer_spec.ts => regex_route_param_spec.ts} | 18 +- 11 files changed, 441 insertions(+), 401 deletions(-) create mode 100644 modules/angular2/src/router/rules/param_route_path.ts delete mode 100644 modules/angular2/src/router/rules/path_recognizer.ts delete mode 100644 modules/angular2/src/router/rules/recognizer.ts delete mode 100644 modules/angular2/src/router/rules/regex_recognizer.ts create mode 100644 modules/angular2/src/router/rules/regex_route_path.ts create mode 100644 modules/angular2/src/router/rules/route_path.ts create mode 100644 modules/angular2/src/router/utils.ts rename modules/angular2/test/router/{path_recognizer_spec.ts => param_route_path_spec.ts} (73%) rename modules/angular2/test/router/{regex_recognizer_spec.ts => regex_route_param_spec.ts} (62%) diff --git a/modules/angular2/src/router/route_registry.ts b/modules/angular2/src/router/route_registry.ts index 8144a41aeb39..1d77886cabc4 100644 --- a/modules/angular2/src/router/route_registry.ts +++ b/modules/angular2/src/router/route_registry.ts @@ -36,7 +36,7 @@ import { } from './instruction'; import {normalizeRouteConfig, assertComponentExists} from './route_config/route_config_nomalizer'; -import {parser, Url, pathSegmentsToUrl} from './rules/url_parser'; +import {parser, Url, pathSegmentsToUrl, serializeParams} from './rules/url_parser'; var _resolveToNull = PromiseWrapper.resolve(null); @@ -394,13 +394,13 @@ export class RouteRegistry { // we'll figure out the rest of the route when we resolve the instruction and // perform a navigation if (isBlank(routeRecognizer.handler.componentType)) { - var compInstruction = routeRecognizer.generateComponentPathValues(routeParams); + var generatedUrl = routeRecognizer.generateComponentPathValues(routeParams); return new UnresolvedInstruction(() => { return routeRecognizer.handler.resolveComponentType().then((_) => { return this._generate(linkParams, ancestorInstructions, prevInstruction, _aux, _originalLink); }); - }, compInstruction['urlPath'], compInstruction['urlParams']); + }, generatedUrl.urlPath, serializeParams(generatedUrl.urlParams)); } componentInstruction = _aux ? rules.generateAuxiliary(routeName, routeParams) : diff --git a/modules/angular2/src/router/rules/param_route_path.ts b/modules/angular2/src/router/rules/param_route_path.ts new file mode 100644 index 000000000000..ee5d56683de5 --- /dev/null +++ b/modules/angular2/src/router/rules/param_route_path.ts @@ -0,0 +1,276 @@ +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, serializeParams} from './url_parser'; +import {RoutePath, GeneratedUrl, MatchedUrl, UrlParams} 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; + if (isPresent(currentUrlSegment)) { + // If this is the root component, read query params. Otherwise, read matrix params. + var paramsSegment = url instanceof RootUrl ? url : currentUrlSegment; + + allParams = isPresent(paramsSegment.params) ? + StringMapWrapper.merge(paramsSegment.params, positionalParams) : + positionalParams; + + urlParams = serializeParams(paramsSegment.params); + + + auxiliary = currentUrlSegment.auxiliary; + } else { + allParams = positionalParams; + auxiliary = []; + urlParams = []; + } + + return new MatchedUrl(urlPath, urlParams, allParams, auxiliary, nextUrlSegment); + } + + + generateUrl(params: UrlParams): 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); + } + + 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, hash; + var hashParts = []; + for(i = 0; i < length; i++) { + hashParts.push(this._segments[i].hash); + } + return hashParts.join('/'); + } + + private _assertValidPath(path: string) { + const RESERVED_CHARS = RegExpWrapper.create('//|\\(|\\)|;|\\?|='); + 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.`); + } + } +} + diff --git a/modules/angular2/src/router/rules/path_recognizer.ts b/modules/angular2/src/router/rules/path_recognizer.ts deleted file mode 100644 index b1f77cd4b255..000000000000 --- a/modules/angular2/src/router/rules/path_recognizer.ts +++ /dev/null @@ -1,286 +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'; -import {GeneratedUrlSegment, RecognizedUrlSegment, Recognizer} from './recognizer'; - -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 PathSegment { - name: string; - generate(params: TouchMap): string; - match(path: string): boolean; -} - -class ContinuationPathSegment implements PathSegment { - name: string = ''; - generate(params: TouchMap): string { return ''; } - match(path: string): boolean { return true; } -} - -class StaticPathSegment implements PathSegment { - name: string = ''; - constructor(public path: string) {} - match(path: string): boolean { return path == this.path; } - generate(params: TouchMap): string { return this.path; } -} - -class DynamicPathSegment implements PathSegment { - 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 StarPathSegment implements PathSegment { - constructor(public name: string) {} - match(path: string): boolean { return true; } - generate(params: TouchMap): string { return normalizeString(params.get(this.name)); } -} - - -const paramMatcher = /^:([^\/]+)$/g; -const 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 DynamicPathSegment(match[1])); - specificity += '1'; - } else if (isPresent(match = RegExpWrapper.firstMatch(wildcardMatcher, segment))) { - results.push(new StarPathSegment(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 ContinuationPathSegment()); - } else { - results.push(new StaticPathSegment(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: PathSegment[]): string { - return segments.map((segment) => { - if (segment instanceof StarPathSegment) { - return '*'; - } else if (segment instanceof ContinuationPathSegment) { - return '...'; - } else if (segment instanceof DynamicPathSegment) { - return ':'; - } else if (segment instanceof StaticPathSegment) { - 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 implements Recognizer { - private _segments: PathSegment[]; - specificity: string; - terminal: boolean = true; - hash: string; - - /** - * Takes a string representing the matcher DSL - */ - 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 ContinuationPathSegment); - } - - recognize(beginningUrlSegment: Url): RecognizedUrlSegment { - var nextUrlSegment = beginningUrlSegment; - 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; - if (isPresent(currentUrlSegment)) { - // If this is the root component, read query params. Otherwise, read matrix params. - var paramsSegment = beginningUrlSegment instanceof RootUrl ? beginningUrlSegment : currentUrlSegment; - - allParams = isPresent(paramsSegment.params) ? - StringMapWrapper.merge(paramsSegment.params, positionalParams) : - positionalParams; - - urlParams = serializeParams(paramsSegment.params); - - - auxiliary = currentUrlSegment.auxiliary; - } else { - allParams = positionalParams; - auxiliary = []; - urlParams = []; - } - - return new RecognizedUrlSegment(urlPath, urlParams, allParams, auxiliary, nextUrlSegment); - } - - - generate(params: {[key: string]: any}): GeneratedUrlSegment { - 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 = serializeParams(nonPositionalParams); - - return new GeneratedUrlSegment(urlPath, urlParams); - } -} diff --git a/modules/angular2/src/router/rules/recognizer.ts b/modules/angular2/src/router/rules/recognizer.ts deleted file mode 100644 index c2aa03ba94dc..000000000000 --- a/modules/angular2/src/router/rules/recognizer.ts +++ /dev/null @@ -1,26 +0,0 @@ -import {Url} from './url_parser'; - -export class RecognizedUrlSegment { - constructor( - public urlPath: string, - public urlParams: string[], - public allParams: {[key: string]: string}, - public auxiliary: Url[], - public nextSegment: Url) {} -} - - -export class GeneratedUrlSegment { - constructor(public urlPath: string, public urlParams: string[]) {} -} - - -export interface Recognizer { - specificity: string; - terminal: boolean; - hash: string; - - recognize(beginningSegment: Url): RecognizedUrlSegment; - generate(params: {[key: string]: any}): GeneratedUrlSegment; -} - diff --git a/modules/angular2/src/router/rules/regex_recognizer.ts b/modules/angular2/src/router/rules/regex_recognizer.ts deleted file mode 100644 index 916eee217900..000000000000 --- a/modules/angular2/src/router/rules/regex_recognizer.ts +++ /dev/null @@ -1,36 +0,0 @@ -import {RegExpWrapper, isBlank} from 'angular2/src/facade/lang'; -import {Url, RootUrl, serializeParams} from './url_parser'; -import {GeneratedUrlSegment, RecognizedUrlSegment, Recognizer} from './recognizer'; - -export class RegexRecognizer implements Recognizer { - public hash: string; - public terminal: boolean = true; - public specificity: string = '2'; - private _regex: RegExp; - - constructor(private _reString: string, private _serializer: (params: {[key: string]: any}) => GeneratedUrlSegment) { - this.hash = this._reString; - this._regex = RegExpWrapper.create(this._reString); - } - - recognize(beginningSegment: Url): RecognizedUrlSegment { - var url = beginningSegment.toString(); - var match = RegExpWrapper.firstMatch(this._regex, url); - - if (isBlank(match)) { - return null; - } - - var params : {[key: string]: string} = {}; - - for (let i = 0; i < match.length; i += 1) { - params[i.toString()] = match[i]; - } - - return new RecognizedUrlSegment(url, [], params, [], null); - } - - generate(params: {[key: string]: any}): GeneratedUrlSegment { - return this._serializer(params); - } -} \ No newline at end of file diff --git a/modules/angular2/src/router/rules/regex_route_path.ts b/modules/angular2/src/router/rules/regex_route_path.ts new file mode 100644 index 000000000000..7854f89ad18b --- /dev/null +++ b/modules/angular2/src/router/rules/regex_route_path.ts @@ -0,0 +1,44 @@ +import {RegExpWrapper, isBlank} from 'angular2/src/facade/lang'; +import {Url, RootUrl, serializeParams} from './url_parser'; +import {RoutePath, GeneratedUrl, MatchedUrl, UrlParams} from './route_path'; + + +export interface RegexSerializer { + (params: UrlParams) : 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 match = RegExpWrapper.firstMatch(this._regex, urlPath); + + if (isBlank(match)) { + return null; + } + + var params : UrlParams = {}; + + for (let i = 0; i < match.length; i += 1) { + params[i.toString()] = match[i]; + } + + return new MatchedUrl(urlPath, [], params, [], null); + } + + generateUrl(params: UrlParams): GeneratedUrl { + return this._serializer(params); + } +} \ No newline at end of file diff --git a/modules/angular2/src/router/rules/route_path.ts b/modules/angular2/src/router/rules/route_path.ts new file mode 100644 index 000000000000..5e8ca96df604 --- /dev/null +++ b/modules/angular2/src/router/rules/route_path.ts @@ -0,0 +1,30 @@ +import {Url} from './url_parser'; + +export interface UrlParams { + [key: string]: any +} + +export class MatchedUrl { + constructor( + public urlPath: string, + public urlParams: string[], + public allParams: UrlParams, + public auxiliary: Url[], + public rest: Url) {} +} + + +export class GeneratedUrl { + constructor( + public urlPath: string, + public urlParams: UrlParams) {} +} + +export interface RoutePath { + specificity: string; + terminal: boolean; + hash: string; + matchUrl(url: Url): MatchedUrl; + generateUrl(params: UrlParams): GeneratedUrl; +} + diff --git a/modules/angular2/src/router/rules/rules.ts b/modules/angular2/src/router/rules/rules.ts index 0a9c0a0c21ad..cba75972e164 100644 --- a/modules/angular2/src/router/rules/rules.ts +++ b/modules/angular2/src/router/rules/rules.ts @@ -4,10 +4,10 @@ import {PromiseWrapper} from 'angular2/src/facade/promise'; import {Map} from 'angular2/src/facade/collection'; import {RouteHandler} from '../route_handlers/route_handler'; -import {Url} from './url_parser'; +import {Url, serializeParams} from './url_parser'; import {ComponentInstruction} from '../instruction'; -import {PathRecognizer} from './path_recognizer'; -import {GeneratedUrlSegment} from './recognizer'; +import {ParamRoutePath} from './param_route_path'; +import {GeneratedUrl, UrlParams} from './route_path'; // RouteMatch objects hold information about a match between a rule and a URL @@ -33,11 +33,11 @@ export interface AbstractRule { } export class RedirectRule implements AbstractRule { - private _pathRecognizer: PathRecognizer; + private _pathRecognizer: ParamRoutePath; public hash: string; constructor(public path: string, public redirectTo: any[]) { - this._pathRecognizer = new PathRecognizer(path); + this._pathRecognizer = new ParamRoutePath(path); this.hash = this._pathRecognizer.hash; } @@ -46,7 +46,7 @@ export class RedirectRule implements AbstractRule { */ recognize(beginningSegment: Url): Promise { var match = null; - if (isPresent(this._pathRecognizer.recognize(beginningSegment))) { + if (isPresent(this._pathRecognizer.matchUrl(beginningSegment))) { match = new RedirectMatch(this.redirectTo, this._pathRecognizer.specificity); } return PromiseWrapper.resolve(match); @@ -61,23 +61,23 @@ export class RedirectRule implements AbstractRule { // represents something like '/foo/:bar' export class RouteRule implements AbstractRule { specificity: string; - terminal: boolean = true; + terminal: boolean; hash: string; private _cache: Map = new Map(); - private _pathRecognizer: PathRecognizer; + private _pathRecognizer: ParamRoutePath; // TODO: cache component instruction instances by params and by ParsedUrl instance constructor(public path: string, public handler: RouteHandler) { - this._pathRecognizer = new PathRecognizer(path); + this._pathRecognizer = new ParamRoutePath(path); this.specificity = this._pathRecognizer.specificity; this.hash = this._pathRecognizer.hash; this.terminal = this._pathRecognizer.terminal; } recognize(beginningSegment: Url): Promise { - var res = this._pathRecognizer.recognize(beginningSegment); + var res = this._pathRecognizer.matchUrl(beginningSegment); if (isBlank(res)) { return null; } @@ -85,33 +85,34 @@ export class RouteRule implements AbstractRule { return this.handler.resolveComponentType().then((_) => { var componentInstruction = this._getInstruction(res.urlPath, res.urlParams, res.allParams); - return new PathMatch(componentInstruction, res.nextSegment, res.auxiliary); + return new PathMatch(componentInstruction, res.rest, res.auxiliary); }); } generate(params: {[key: string]: any}): ComponentInstruction { - var generated = this._pathRecognizer.generate(params); + var generated = this._pathRecognizer.generateUrl(params); var urlPath = generated.urlPath; var urlParams = generated.urlParams; return this._getInstruction(urlPath, urlParams, params); } - generateComponentPathValues(params: {[key: string]: any}): GeneratedUrlSegment { - return this._pathRecognizer.generate(params); + generateComponentPathValues(params: {[key: string]: any}): GeneratedUrl { + return this._pathRecognizer.generateUrl(params); } - private _getInstruction(urlPath: string, urlParams: string[], + private _getInstruction(urlPath: string, urlParams: UrlParams, params: {[key: string]: any}): ComponentInstruction { if (isBlank(this.handler.componentType)) { throw new BaseException(`Tried to get instruction before the type was loaded.`); } + var serializedParams = serializeParams(urlParams); - var hashKey = urlPath + '?' + urlParams.join('?'); + var hashKey = urlPath + '?' + serializedParams.join('?'); if (this._cache.has(hashKey)) { return this._cache.get(hashKey); } var instruction = - new ComponentInstruction(urlPath, urlParams, this.handler.data, this.handler.componentType, + new ComponentInstruction(urlPath, serializedParams, this.handler.data, this.handler.componentType, this.terminal, this.specificity, params); this._cache.set(hashKey, instruction); diff --git a/modules/angular2/src/router/utils.ts b/modules/angular2/src/router/utils.ts new file mode 100644 index 000000000000..711de69d2312 --- /dev/null +++ b/modules/angular2/src/router/utils.ts @@ -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(); + } +} diff --git a/modules/angular2/test/router/path_recognizer_spec.ts b/modules/angular2/test/router/param_route_path_spec.ts similarity index 73% rename from modules/angular2/test/router/path_recognizer_spec.ts rename to modules/angular2/test/router/param_route_path_spec.ts index a3900cf6487d..5159d6bc09f0 100644 --- a/modules/angular2/test/router/path_recognizer_spec.ts +++ b/modules/angular2/test/router/param_route_path_spec.ts @@ -10,92 +10,92 @@ import { SpyObject } from 'angular2/testing_internal'; -import {PathRecognizer} from 'angular2/src/router/rules/path_recognizer'; +import {ParamRoutePath} from 'angular2/src/router/rules/param_route_path'; import {parser, Url} from 'angular2/src/router/rules/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); + 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); + 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); + 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); + 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); + 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); + 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); + 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); + var match = rec.matchUrl(url); expect(match['urlPath']).toEqual('wild/super;variable=value/anotherPartAfterSlash'); }); }); diff --git a/modules/angular2/test/router/regex_recognizer_spec.ts b/modules/angular2/test/router/regex_route_param_spec.ts similarity index 62% rename from modules/angular2/test/router/regex_recognizer_spec.ts rename to modules/angular2/test/router/regex_route_param_spec.ts index 8db41dd228ba..cb4b41de9e35 100644 --- a/modules/angular2/test/router/regex_recognizer_spec.ts +++ b/modules/angular2/test/router/regex_route_param_spec.ts @@ -10,34 +10,34 @@ import { SpyObject } from 'angular2/testing_internal'; -import {GeneratedUrlSegment} from 'angular2/src/router/rules/recognizer'; -import {RegexRecognizer} from 'angular2/src/router/rules/regex_recognizer'; +import {GeneratedUrl} from 'angular2/src/router/rules/route_path'; +import {RegexRoutePath} from 'angular2/src/router/rules/regex_route_path'; import {parser, Url} from 'angular2/src/router/rules/url_parser'; export function main() { - describe('RegexRecognizer', () => { + describe('RegexRoutePath', () => { it('should throw when given an invalid regex', () => { - expect(() => new RegexRecognizer('[abc', emptySerializer)) + expect(() => new RegexRoutePath('[abc', emptySerializer)) .toThrowError('Invalid regular expression: /[abc/: Unterminated character class'); }); it('should parse a single param using capture groups', () => { - var rec = new RegexRecognizer('^(.+)$', emptySerializer); + var rec = new RegexRoutePath('^(.+)$', emptySerializer); var url = parser.parse('hello'); - var match = rec.recognize(url); + var match = rec.matchUrl(url); expect(match.allParams).toEqual({ '0': 'hello', '1': 'hello' }); }); it('should parse multiple params using capture groups', () => { - var rec = new RegexRecognizer('^(.+)\\.(.+)$', emptySerializer); + var rec = new RegexRoutePath('^(.+)\\.(.+)$', emptySerializer); var url = parser.parse('hello.goodbye'); - var match = rec.recognize(url); + var match = rec.matchUrl(url); expect(match.allParams).toEqual({ '0': 'hello.goodbye', '1': 'hello', '2': 'goodbye' }); }); function emptySerializer(params) { - return new GeneratedUrlSegment('', []); + return new GeneratedUrl('', []); } }); } From 16340f35f64548cb20c95373c990b6329f348360 Mon Sep 17 00:00:00 2001 From: Peter Bacon Darwin Date: Wed, 17 Feb 2016 11:56:44 +0000 Subject: [PATCH 19/43] style(router): fix formatting --- modules/angular1_router/src/ng_outlet.ts | 1 - .../angular2/src/router/route_definition.ts | 4 +-- modules/angular2/src/router/route_registry.ts | 6 ++-- .../src/router/rules/param_route_path.ts | 35 +++++++++---------- .../src/router/rules/regex_route_path.ts | 14 +++----- .../angular2/src/router/rules/route_path.ts | 17 +++------ modules/angular2/src/router/rules/rule_set.ts | 14 ++++---- modules/angular2/src/router/rules/rules.ts | 11 +++--- .../test/router/integration/bootstrap_spec.ts | 7 +++- .../integration/impl/aux_route_spec_impl.ts | 7 +++- .../test/router/regex_route_param_spec.ts | 8 ++--- modules/angular2/test/router/router_spec.ts | 7 +++- 12 files changed, 61 insertions(+), 70 deletions(-) diff --git a/modules/angular1_router/src/ng_outlet.ts b/modules/angular1_router/src/ng_outlet.ts index 273a6ffd6a14..f6e346014a93 100644 --- a/modules/angular1_router/src/ng_outlet.ts +++ b/modules/angular1_router/src/ng_outlet.ts @@ -200,7 +200,6 @@ function ngOutletFillContentDirective($compile) { - function routerTriggerDirective($q) { return { require: '^ngOutlet', diff --git a/modules/angular2/src/router/route_definition.ts b/modules/angular2/src/router/route_definition.ts index fb58f5e8dfd1..376242625f27 100644 --- a/modules/angular2/src/router/route_definition.ts +++ b/modules/angular2/src/router/route_definition.ts @@ -15,8 +15,8 @@ export interface RouteDefinition { path?: string; aux?: string; regex?: string; - //TODO: - //serializer?: + // TODO: + // serializer?: component?: Type | ComponentDefinition; loader?: Function; redirectTo?: any[]; diff --git a/modules/angular2/src/router/route_registry.ts b/modules/angular2/src/router/route_registry.ts index 1d77886cabc4..feac0db2ed5d 100644 --- a/modules/angular2/src/router/route_registry.ts +++ b/modules/angular2/src/router/route_registry.ts @@ -166,8 +166,7 @@ export class RouteRegistry { // Matches some beginning part of the given URL var possibleMatches: Promise[] = - _aux ? rules.recognizeAuxiliary(parsedUrl) : - rules.recognize(parsedUrl); + _aux ? rules.recognizeAuxiliary(parsedUrl) : rules.recognize(parsedUrl); var matchPromises: Promise[] = possibleMatches.map( (candidate: Promise) => candidate.then((candidate: RouteMatch) => { @@ -382,8 +381,7 @@ export class RouteRegistry { linkParamIndex += 1; } } - var routeRecognizer = - (_aux ? rules.auxRulesByName : rules.rulesByName).get(routeName); + var routeRecognizer = (_aux ? rules.auxRulesByName : rules.rulesByName).get(routeName); if (isBlank(routeRecognizer)) { throw new BaseException( diff --git a/modules/angular2/src/router/rules/param_route_path.ts b/modules/angular2/src/router/rules/param_route_path.ts index ee5d56683de5..1a0e0de2843a 100644 --- a/modules/angular2/src/router/rules/param_route_path.ts +++ b/modules/angular2/src/router/rules/param_route_path.ts @@ -1,9 +1,4 @@ -import { - RegExpWrapper, - StringWrapper, - isPresent, - isBlank -} from 'angular2/src/facade/lang'; +import {RegExpWrapper, StringWrapper, isPresent, isBlank} from 'angular2/src/facade/lang'; import {BaseException} from 'angular2/src/facade/exceptions'; import {StringMapWrapper} from 'angular2/src/facade/collection'; @@ -46,9 +41,7 @@ class StaticPathSegment implements PathSegment { name: string = ''; specificity = '2'; hash: string; - constructor(public path: string) { - this.hash = path; - } + constructor(public path: string) { this.hash = path; } match(path: string): boolean { return path == this.path; } generate(params: TouchMap): string { return this.path; } } @@ -115,7 +108,7 @@ export class ParamRoutePath implements RoutePath { var nextUrlSegment = url; var currentUrlSegment: Url; var positionalParams = {}; - var captured : string[] = []; + var captured: string[] = []; for (var i = 0; i < this._segments.length; i += 1) { var pathSegment = this._segments[i]; @@ -214,11 +207,13 @@ export class ParamRoutePath implements RoutePath { if (isPresent(match = RegExpWrapper.firstMatch(DynamicPathSegment.paramMatcher, segment))) { this._segments.push(new DynamicPathSegment(match[1])); - } else if (isPresent(match = RegExpWrapper.firstMatch(StarPathSegment.wildcardMatcher, segment))) { + } 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}".`); + throw new BaseException( + `Unexpected "..." before the end of the path for "${routePath}".`); } this._segments.push(new ContinuationPathSegment()); } else { @@ -227,10 +222,13 @@ export class ParamRoutePath implements RoutePath { } } - 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 + 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 @@ -249,12 +247,12 @@ export class ParamRoutePath implements RoutePath { return specificity; } - private _calculateHash() : string{ + 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, hash; var hashParts = []; - for(i = 0; i < length; i++) { + for (i = 0; i < length; i++) { hashParts.push(this._segments[i].hash); } return hashParts.join('/'); @@ -273,4 +271,3 @@ export class ParamRoutePath implements RoutePath { } } } - diff --git a/modules/angular2/src/router/rules/regex_route_path.ts b/modules/angular2/src/router/rules/regex_route_path.ts index 7854f89ad18b..01d9ba296ecf 100644 --- a/modules/angular2/src/router/rules/regex_route_path.ts +++ b/modules/angular2/src/router/rules/regex_route_path.ts @@ -3,9 +3,7 @@ import {Url, RootUrl, serializeParams} from './url_parser'; import {RoutePath, GeneratedUrl, MatchedUrl, UrlParams} from './route_path'; -export interface RegexSerializer { - (params: UrlParams) : GeneratedUrl -} +export interface RegexSerializer { (params: UrlParams): GeneratedUrl } export class RegexRoutePath implements RoutePath { public hash: string; @@ -14,9 +12,7 @@ export class RegexRoutePath implements RoutePath { private _regex: RegExp; - constructor( - private _reString: string, - private _serializer: RegexSerializer) { + constructor(private _reString: string, private _serializer: RegexSerializer) { this.hash = this._reString; this._regex = RegExpWrapper.create(this._reString); } @@ -29,7 +25,7 @@ export class RegexRoutePath implements RoutePath { return null; } - var params : UrlParams = {}; + var params: UrlParams = {}; for (let i = 0; i < match.length; i += 1) { params[i.toString()] = match[i]; @@ -38,7 +34,5 @@ export class RegexRoutePath implements RoutePath { return new MatchedUrl(urlPath, [], params, [], null); } - generateUrl(params: UrlParams): GeneratedUrl { - return this._serializer(params); - } + generateUrl(params: UrlParams): GeneratedUrl { return this._serializer(params); } } \ No newline at end of file diff --git a/modules/angular2/src/router/rules/route_path.ts b/modules/angular2/src/router/rules/route_path.ts index 5e8ca96df604..78ec010d606c 100644 --- a/modules/angular2/src/router/rules/route_path.ts +++ b/modules/angular2/src/router/rules/route_path.ts @@ -1,23 +1,15 @@ import {Url} from './url_parser'; -export interface UrlParams { - [key: string]: any -} +export interface UrlParams { [key: string]: any } export class MatchedUrl { - constructor( - public urlPath: string, - public urlParams: string[], - public allParams: UrlParams, - public auxiliary: Url[], - public rest: Url) {} + constructor(public urlPath: string, public urlParams: string[], public allParams: UrlParams, + public auxiliary: Url[], public rest: Url) {} } export class GeneratedUrl { - constructor( - public urlPath: string, - public urlParams: UrlParams) {} + constructor(public urlPath: string, public urlParams: UrlParams) {} } export interface RoutePath { @@ -27,4 +19,3 @@ export interface RoutePath { matchUrl(url: Url): MatchedUrl; generateUrl(params: UrlParams): GeneratedUrl; } - diff --git a/modules/angular2/src/router/rules/rule_set.ts b/modules/angular2/src/router/rules/rule_set.ts index ca23ad1eb27f..b3d2d92fe7b2 100644 --- a/modules/angular2/src/router/rules/rule_set.ts +++ b/modules/angular2/src/router/rules/rule_set.ts @@ -3,14 +3,14 @@ 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 { - AbstractRule, - RouteRule, - RedirectRule, - RouteMatch, - PathMatch -} from './rules'; -import {Route, AsyncRoute, AuxRoute, Redirect, RouteDefinition} from '../route_config/route_config_impl'; + 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 {Url} from './url_parser'; diff --git a/modules/angular2/src/router/rules/rules.ts b/modules/angular2/src/router/rules/rules.ts index cba75972e164..c2a387674a04 100644 --- a/modules/angular2/src/router/rules/rules.ts +++ b/modules/angular2/src/router/rules/rules.ts @@ -83,8 +83,7 @@ export class RouteRule implements AbstractRule { } return this.handler.resolveComponentType().then((_) => { - var componentInstruction = - this._getInstruction(res.urlPath, res.urlParams, res.allParams); + var componentInstruction = this._getInstruction(res.urlPath, res.urlParams, res.allParams); return new PathMatch(componentInstruction, res.rest, res.auxiliary); }); } @@ -96,7 +95,7 @@ export class RouteRule implements AbstractRule { return this._getInstruction(urlPath, urlParams, params); } - generateComponentPathValues(params: {[key: string]: any}): GeneratedUrl { + generateComponentPathValues(params: {[key: string]: any}): GeneratedUrl { return this._pathRecognizer.generateUrl(params); } @@ -111,9 +110,9 @@ export class RouteRule implements AbstractRule { if (this._cache.has(hashKey)) { return this._cache.get(hashKey); } - var instruction = - new ComponentInstruction(urlPath, serializedParams, this.handler.data, this.handler.componentType, - this.terminal, this.specificity, params); + var instruction = new ComponentInstruction(urlPath, serializedParams, this.handler.data, + this.handler.componentType, this.terminal, + this.specificity, params); this._cache.set(hashKey, instruction); return instruction; diff --git a/modules/angular2/test/router/integration/bootstrap_spec.ts b/modules/angular2/test/router/integration/bootstrap_spec.ts index 08595f3b49f8..45e657dcc65e 100644 --- a/modules/angular2/test/router/integration/bootstrap_spec.ts +++ b/modules/angular2/test/router/integration/bootstrap_spec.ts @@ -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/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 { diff --git a/modules/angular2/test/router/integration/impl/aux_route_spec_impl.ts b/modules/angular2/test/router/integration/impl/aux_route_spec_impl.ts index 3fcb7368ad2a..2314b890c3d4 100644 --- a/modules/angular2/test/router/integration/impl/aux_route_spec_impl.ts +++ b/modules/angular2/test/router/integration/impl/aux_route_spec_impl.ts @@ -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/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'; diff --git a/modules/angular2/test/router/regex_route_param_spec.ts b/modules/angular2/test/router/regex_route_param_spec.ts index cb4b41de9e35..e27af03fb7d8 100644 --- a/modules/angular2/test/router/regex_route_param_spec.ts +++ b/modules/angular2/test/router/regex_route_param_spec.ts @@ -26,18 +26,16 @@ export function main() { var rec = new RegexRoutePath('^(.+)$', emptySerializer); var url = parser.parse('hello'); var match = rec.matchUrl(url); - expect(match.allParams).toEqual({ '0': 'hello', '1': 'hello' }); + 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' }); + expect(match.allParams).toEqual({'0': 'hello.goodbye', '1': 'hello', '2': 'goodbye'}); }); - function emptySerializer(params) { - return new GeneratedUrl('', []); - } + function emptySerializer(params) { return new GeneratedUrl('', []); } }); } diff --git a/modules/angular2/test/router/router_spec.ts b/modules/angular2/test/router/router_spec.ts index abf4f75edd46..f8056f32c94a 100644 --- a/modules/angular2/test/router/router_spec.ts +++ b/modules/angular2/test/router/router_spec.ts @@ -21,7 +21,12 @@ import {SpyLocation} from 'angular2/src/mock/location_mock'; 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/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'; From 2ce29abd3e972ff5ba1c5f8515d0f6c8fdb3e804 Mon Sep 17 00:00:00 2001 From: Peter Bacon Darwin Date: Wed, 17 Feb 2016 14:21:23 +0000 Subject: [PATCH 20/43] refactor(router): move route_handlers into rules folder --- .../router/{ => rules}/route_handlers/async_route_handler.ts | 0 .../src/router/{ => rules}/route_handlers/route_handler.ts | 0 .../router/{ => rules}/route_handlers/sync_route_handler.ts | 0 modules/angular2/src/router/rules/rule_set.ts | 4 ++-- modules/angular2/src/router/rules/rules.ts | 2 +- 5 files changed, 3 insertions(+), 3 deletions(-) rename modules/angular2/src/router/{ => rules}/route_handlers/async_route_handler.ts (100%) rename modules/angular2/src/router/{ => rules}/route_handlers/route_handler.ts (100%) rename modules/angular2/src/router/{ => rules}/route_handlers/sync_route_handler.ts (100%) diff --git a/modules/angular2/src/router/route_handlers/async_route_handler.ts b/modules/angular2/src/router/rules/route_handlers/async_route_handler.ts similarity index 100% rename from modules/angular2/src/router/route_handlers/async_route_handler.ts rename to modules/angular2/src/router/rules/route_handlers/async_route_handler.ts diff --git a/modules/angular2/src/router/route_handlers/route_handler.ts b/modules/angular2/src/router/rules/route_handlers/route_handler.ts similarity index 100% rename from modules/angular2/src/router/route_handlers/route_handler.ts rename to modules/angular2/src/router/rules/route_handlers/route_handler.ts diff --git a/modules/angular2/src/router/route_handlers/sync_route_handler.ts b/modules/angular2/src/router/rules/route_handlers/sync_route_handler.ts similarity index 100% rename from modules/angular2/src/router/route_handlers/sync_route_handler.ts rename to modules/angular2/src/router/rules/route_handlers/sync_route_handler.ts diff --git a/modules/angular2/src/router/rules/rule_set.ts b/modules/angular2/src/router/rules/rule_set.ts index b3d2d92fe7b2..36762db7f185 100644 --- a/modules/angular2/src/router/rules/rule_set.ts +++ b/modules/angular2/src/router/rules/rule_set.ts @@ -11,8 +11,8 @@ import { 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 {AsyncRouteHandler} from './route_handlers/async_route_handler'; +import {SyncRouteHandler} from './route_handlers/sync_route_handler'; import {Url} from './url_parser'; import {ComponentInstruction} from '../instruction'; diff --git a/modules/angular2/src/router/rules/rules.ts b/modules/angular2/src/router/rules/rules.ts index c2a387674a04..4f1700d8f88c 100644 --- a/modules/angular2/src/router/rules/rules.ts +++ b/modules/angular2/src/router/rules/rules.ts @@ -3,7 +3,7 @@ import {BaseException} from 'angular2/src/facade/exceptions'; import {PromiseWrapper} from 'angular2/src/facade/promise'; import {Map} from 'angular2/src/facade/collection'; -import {RouteHandler} from '../route_handlers/route_handler'; +import {RouteHandler} from './route_handlers/route_handler'; import {Url, serializeParams} from './url_parser'; import {ComponentInstruction} from '../instruction'; import {ParamRoutePath} from './param_route_path'; From 30b36eeb3ea20b9b52bfd60cb2a3d39009cdc858 Mon Sep 17 00:00:00 2001 From: Peter Bacon Darwin Date: Wed, 17 Feb 2016 14:40:30 +0000 Subject: [PATCH 21/43] refactor(router): move location specs into their own folder --- .../test/router/{ => location}/hash_location_strategy_spec.ts | 2 +- modules/angular2/test/router/{ => location}/location_spec.ts | 0 .../test/router/{ => location}/path_location_strategy_spec.ts | 2 +- 3 files changed, 2 insertions(+), 2 deletions(-) rename modules/angular2/test/router/{ => location}/hash_location_strategy_spec.ts (99%) rename modules/angular2/test/router/{ => location}/location_spec.ts (100%) rename modules/angular2/test/router/{ => location}/path_location_strategy_spec.ts (99%) diff --git a/modules/angular2/test/router/hash_location_strategy_spec.ts b/modules/angular2/test/router/location/hash_location_strategy_spec.ts similarity index 99% rename from modules/angular2/test/router/hash_location_strategy_spec.ts rename to modules/angular2/test/router/location/hash_location_strategy_spec.ts index 0900de823a84..d60a8e3f1da5 100644 --- a/modules/angular2/test/router/hash_location_strategy_spec.ts +++ b/modules/angular2/test/router/location/hash_location_strategy_spec.ts @@ -18,7 +18,7 @@ import {CONST_EXPR} from 'angular2/src/facade/lang'; import {PlatformLocation} from 'angular2/src/router/location/platform_location'; import {LocationStrategy, APP_BASE_HREF} from 'angular2/src/router/location/location_strategy'; import {HashLocationStrategy} from 'angular2/src/router/location/hash_location_strategy'; -import {SpyPlatformLocation} from './spies'; +import {SpyPlatformLocation} from '../spies'; export function main() { describe('HashLocationStrategy', () => { diff --git a/modules/angular2/test/router/location_spec.ts b/modules/angular2/test/router/location/location_spec.ts similarity index 100% rename from modules/angular2/test/router/location_spec.ts rename to modules/angular2/test/router/location/location_spec.ts diff --git a/modules/angular2/test/router/path_location_strategy_spec.ts b/modules/angular2/test/router/location/path_location_strategy_spec.ts similarity index 99% rename from modules/angular2/test/router/path_location_strategy_spec.ts rename to modules/angular2/test/router/location/path_location_strategy_spec.ts index 2ac63b23ad80..c884b1e6bb07 100644 --- a/modules/angular2/test/router/path_location_strategy_spec.ts +++ b/modules/angular2/test/router/location/path_location_strategy_spec.ts @@ -18,7 +18,7 @@ import {CONST_EXPR} from 'angular2/src/facade/lang'; 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'; +import {SpyPlatformLocation} from '../spies'; export function main() { describe('PathLocationStrategy', () => { From 0d7595f82b10db062ab57ebb6044f378e6015fac Mon Sep 17 00:00:00 2001 From: Peter Bacon Darwin Date: Wed, 17 Feb 2016 14:41:53 +0000 Subject: [PATCH 22/43] refactor(router): move rule tests into their own folder --- .../router/{ => rules/route_paths}/param_route_path_spec.ts | 4 ++-- .../{ => rules/route_paths}/regex_route_param_spec.ts | 6 +++--- modules/angular2/test/router/{ => rules}/rule_set_spec.ts | 2 +- 3 files changed, 6 insertions(+), 6 deletions(-) rename modules/angular2/test/router/{ => rules/route_paths}/param_route_path_spec.ts (96%) rename modules/angular2/test/router/{ => rules/route_paths}/regex_route_param_spec.ts (88%) rename modules/angular2/test/router/{ => rules}/rule_set_spec.ts (99%) diff --git a/modules/angular2/test/router/param_route_path_spec.ts b/modules/angular2/test/router/rules/route_paths/param_route_path_spec.ts similarity index 96% rename from modules/angular2/test/router/param_route_path_spec.ts rename to modules/angular2/test/router/rules/route_paths/param_route_path_spec.ts index 5159d6bc09f0..09031d4707ac 100644 --- a/modules/angular2/test/router/param_route_path_spec.ts +++ b/modules/angular2/test/router/rules/route_paths/param_route_path_spec.ts @@ -10,8 +10,8 @@ import { SpyObject } from 'angular2/testing_internal'; -import {ParamRoutePath} from 'angular2/src/router/rules/param_route_path'; -import {parser, Url} from 'angular2/src/router/rules/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', () => { diff --git a/modules/angular2/test/router/regex_route_param_spec.ts b/modules/angular2/test/router/rules/route_paths/regex_route_param_spec.ts similarity index 88% rename from modules/angular2/test/router/regex_route_param_spec.ts rename to modules/angular2/test/router/rules/route_paths/regex_route_param_spec.ts index e27af03fb7d8..2cb5fb98b9dc 100644 --- a/modules/angular2/test/router/regex_route_param_spec.ts +++ b/modules/angular2/test/router/rules/route_paths/regex_route_param_spec.ts @@ -10,9 +10,9 @@ import { SpyObject } from 'angular2/testing_internal'; -import {GeneratedUrl} from 'angular2/src/router/rules/route_path'; -import {RegexRoutePath} from 'angular2/src/router/rules/regex_route_path'; -import {parser, Url} from 'angular2/src/router/rules/url_parser'; +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'; export function main() { describe('RegexRoutePath', () => { diff --git a/modules/angular2/test/router/rule_set_spec.ts b/modules/angular2/test/router/rules/rule_set_spec.ts similarity index 99% rename from modules/angular2/test/router/rule_set_spec.ts rename to modules/angular2/test/router/rules/rule_set_spec.ts index 329e71387d83..c1106d266e04 100644 --- a/modules/angular2/test/router/rule_set_spec.ts +++ b/modules/angular2/test/router/rules/rule_set_spec.ts @@ -16,7 +16,7 @@ import {RouteMatch, PathMatch, RedirectMatch} from 'angular2/src/router/rules/ru import {RuleSet} from 'angular2/src/router/rules/rule_set'; import {Route, Redirect} from 'angular2/src/router/route_config/route_config_decorator'; -import {parser} from 'angular2/src/router/rules/url_parser'; +import {parser} from 'angular2/src/router/url_parser'; import {PromiseWrapper} from 'angular2/src/facade/promise'; From 6e50b0888966e8a86b5694d47118ca179a2b11c0 Mon Sep 17 00:00:00 2001 From: Peter Bacon Darwin Date: Wed, 17 Feb 2016 14:42:28 +0000 Subject: [PATCH 23/43] refactor(router): move directive tests into their own folder --- .../angular2/test/router/{ => directives}/router_link_spec.ts | 0 .../test/router/{ => directives}/router_link_transform_spec.ts | 2 +- 2 files changed, 1 insertion(+), 1 deletion(-) rename modules/angular2/test/router/{ => directives}/router_link_spec.ts (100%) rename modules/angular2/test/router/{ => directives}/router_link_transform_spec.ts (97%) diff --git a/modules/angular2/test/router/router_link_spec.ts b/modules/angular2/test/router/directives/router_link_spec.ts similarity index 100% rename from modules/angular2/test/router/router_link_spec.ts rename to modules/angular2/test/router/directives/router_link_spec.ts diff --git a/modules/angular2/test/router/router_link_transform_spec.ts b/modules/angular2/test/router/directives/router_link_transform_spec.ts similarity index 97% rename from modules/angular2/test/router/router_link_transform_spec.ts rename to modules/angular2/test/router/directives/router_link_transform_spec.ts index 7cb81dd99f1f..8a1642b83435 100644 --- a/modules/angular2/test/router/router_link_transform_spec.ts +++ b/modules/angular2/test/router/directives/router_link_transform_spec.ts @@ -16,7 +16,7 @@ import {Injector, provide} from 'angular2/core'; import {CONST_EXPR} from 'angular2/src/facade/lang'; 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'; export function main() { From 89e0258c566e6d4bad6594a443e735c1f033c6a5 Mon Sep 17 00:00:00 2001 From: Peter Bacon Darwin Date: Wed, 17 Feb 2016 14:42:59 +0000 Subject: [PATCH 24/43] refactor(router): move router config tests into their own folder --- .../test/router/{ => route_config}/route_config_spec.dart | 0 .../angular2/test/router/{ => route_config}/route_config_spec.ts | 0 2 files changed, 0 insertions(+), 0 deletions(-) rename modules/angular2/test/router/{ => route_config}/route_config_spec.dart (100%) rename modules/angular2/test/router/{ => route_config}/route_config_spec.ts (100%) diff --git a/modules/angular2/test/router/route_config_spec.dart b/modules/angular2/test/router/route_config/route_config_spec.dart similarity index 100% rename from modules/angular2/test/router/route_config_spec.dart rename to modules/angular2/test/router/route_config/route_config_spec.dart diff --git a/modules/angular2/test/router/route_config_spec.ts b/modules/angular2/test/router/route_config/route_config_spec.ts similarity index 100% rename from modules/angular2/test/router/route_config_spec.ts rename to modules/angular2/test/router/route_config/route_config_spec.ts From e72f142b8ae090a4d1a5bde076fa0334f445853c Mon Sep 17 00:00:00 2001 From: Peter Bacon Darwin Date: Wed, 17 Feb 2016 14:47:09 +0000 Subject: [PATCH 25/43] refactor(router): move urlParser back up to router folder --- modules/angular2/src/router/route_registry.ts | 2 +- modules/angular2/src/router/rules/param_route_path.ts | 2 +- modules/angular2/src/router/rules/regex_route_path.ts | 2 +- modules/angular2/src/router/rules/route_path.ts | 2 +- modules/angular2/src/router/rules/rule_set.ts | 2 +- modules/angular2/src/router/rules/rules.ts | 2 +- modules/angular2/src/router/{rules => }/url_parser.ts | 0 modules/angular2/test/router/url_parser_spec.ts | 2 +- 8 files changed, 7 insertions(+), 7 deletions(-) rename modules/angular2/src/router/{rules => }/url_parser.ts (100%) diff --git a/modules/angular2/src/router/route_registry.ts b/modules/angular2/src/router/route_registry.ts index feac0db2ed5d..07234c31dd26 100644 --- a/modules/angular2/src/router/route_registry.ts +++ b/modules/angular2/src/router/route_registry.ts @@ -36,7 +36,7 @@ import { } from './instruction'; import {normalizeRouteConfig, assertComponentExists} from './route_config/route_config_nomalizer'; -import {parser, Url, pathSegmentsToUrl, serializeParams} from './rules/url_parser'; +import {parser, Url, pathSegmentsToUrl, serializeParams} from './url_parser'; var _resolveToNull = PromiseWrapper.resolve(null); diff --git a/modules/angular2/src/router/rules/param_route_path.ts b/modules/angular2/src/router/rules/param_route_path.ts index 1a0e0de2843a..a0ec661b8e3e 100644 --- a/modules/angular2/src/router/rules/param_route_path.ts +++ b/modules/angular2/src/router/rules/param_route_path.ts @@ -3,7 +3,7 @@ import {BaseException} from 'angular2/src/facade/exceptions'; import {StringMapWrapper} from 'angular2/src/facade/collection'; import {TouchMap, normalizeString} from '../utils'; -import {Url, RootUrl, serializeParams} from './url_parser'; +import {Url, RootUrl, serializeParams} from '../url_parser'; import {RoutePath, GeneratedUrl, MatchedUrl, UrlParams} from './route_path'; diff --git a/modules/angular2/src/router/rules/regex_route_path.ts b/modules/angular2/src/router/rules/regex_route_path.ts index 01d9ba296ecf..64df35fe90a2 100644 --- a/modules/angular2/src/router/rules/regex_route_path.ts +++ b/modules/angular2/src/router/rules/regex_route_path.ts @@ -1,5 +1,5 @@ import {RegExpWrapper, isBlank} from 'angular2/src/facade/lang'; -import {Url, RootUrl, serializeParams} from './url_parser'; +import {Url, RootUrl, serializeParams} from '../url_parser'; import {RoutePath, GeneratedUrl, MatchedUrl, UrlParams} from './route_path'; diff --git a/modules/angular2/src/router/rules/route_path.ts b/modules/angular2/src/router/rules/route_path.ts index 78ec010d606c..5350f03314b3 100644 --- a/modules/angular2/src/router/rules/route_path.ts +++ b/modules/angular2/src/router/rules/route_path.ts @@ -1,4 +1,4 @@ -import {Url} from './url_parser'; +import {Url} from '../url_parser'; export interface UrlParams { [key: string]: any } diff --git a/modules/angular2/src/router/rules/rule_set.ts b/modules/angular2/src/router/rules/rule_set.ts index 36762db7f185..0e2f80368773 100644 --- a/modules/angular2/src/router/rules/rule_set.ts +++ b/modules/angular2/src/router/rules/rule_set.ts @@ -13,7 +13,7 @@ import { } from '../route_config/route_config_impl'; import {AsyncRouteHandler} from './route_handlers/async_route_handler'; import {SyncRouteHandler} from './route_handlers/sync_route_handler'; -import {Url} from './url_parser'; +import {Url} from '../url_parser'; import {ComponentInstruction} from '../instruction'; diff --git a/modules/angular2/src/router/rules/rules.ts b/modules/angular2/src/router/rules/rules.ts index 4f1700d8f88c..2e6da86fab91 100644 --- a/modules/angular2/src/router/rules/rules.ts +++ b/modules/angular2/src/router/rules/rules.ts @@ -4,7 +4,7 @@ import {PromiseWrapper} from 'angular2/src/facade/promise'; import {Map} from 'angular2/src/facade/collection'; import {RouteHandler} from './route_handlers/route_handler'; -import {Url, serializeParams} from './url_parser'; +import {Url, serializeParams} from '../url_parser'; import {ComponentInstruction} from '../instruction'; import {ParamRoutePath} from './param_route_path'; import {GeneratedUrl, UrlParams} from './route_path'; diff --git a/modules/angular2/src/router/rules/url_parser.ts b/modules/angular2/src/router/url_parser.ts similarity index 100% rename from modules/angular2/src/router/rules/url_parser.ts rename to modules/angular2/src/router/url_parser.ts diff --git a/modules/angular2/test/router/url_parser_spec.ts b/modules/angular2/test/router/url_parser_spec.ts index 96c30ee21e64..12fd02c25ce6 100644 --- a/modules/angular2/test/router/url_parser_spec.ts +++ b/modules/angular2/test/router/url_parser_spec.ts @@ -10,7 +10,7 @@ import { SpyObject } from 'angular2/testing_internal'; -import {UrlParser, Url} from 'angular2/src/router/rules/url_parser'; +import {UrlParser, Url} from 'angular2/src/router/url_parser'; export function main() { From b998956af4524d8083e75d5a4ecf2fd3769426a1 Mon Sep 17 00:00:00 2001 From: Peter Bacon Darwin Date: Wed, 17 Feb 2016 15:06:29 +0000 Subject: [PATCH 26/43] refactor(router): move routePath stuff in its own subfolder --- .../src/router/rules/{ => route_paths}/param_route_path.ts | 4 ++-- .../src/router/rules/{ => route_paths}/regex_route_path.ts | 2 +- .../angular2/src/router/rules/{ => route_paths}/route_path.ts | 2 +- modules/angular2/src/router/rules/rules.ts | 4 ++-- 4 files changed, 6 insertions(+), 6 deletions(-) rename modules/angular2/src/router/rules/{ => route_paths}/param_route_path.ts (98%) rename modules/angular2/src/router/rules/{ => route_paths}/regex_route_path.ts (94%) rename modules/angular2/src/router/rules/{ => route_paths}/route_path.ts (93%) diff --git a/modules/angular2/src/router/rules/param_route_path.ts b/modules/angular2/src/router/rules/route_paths/param_route_path.ts similarity index 98% rename from modules/angular2/src/router/rules/param_route_path.ts rename to modules/angular2/src/router/rules/route_paths/param_route_path.ts index a0ec661b8e3e..a0d14bda9d1b 100644 --- a/modules/angular2/src/router/rules/param_route_path.ts +++ b/modules/angular2/src/router/rules/route_paths/param_route_path.ts @@ -2,8 +2,8 @@ import {RegExpWrapper, StringWrapper, isPresent, isBlank} from 'angular2/src/fac import {BaseException} from 'angular2/src/facade/exceptions'; import {StringMapWrapper} from 'angular2/src/facade/collection'; -import {TouchMap, normalizeString} from '../utils'; -import {Url, RootUrl, serializeParams} from '../url_parser'; +import {TouchMap, normalizeString} from '../../utils'; +import {Url, RootUrl, serializeParams} from '../../url_parser'; import {RoutePath, GeneratedUrl, MatchedUrl, UrlParams} from './route_path'; diff --git a/modules/angular2/src/router/rules/regex_route_path.ts b/modules/angular2/src/router/rules/route_paths/regex_route_path.ts similarity index 94% rename from modules/angular2/src/router/rules/regex_route_path.ts rename to modules/angular2/src/router/rules/route_paths/regex_route_path.ts index 64df35fe90a2..bf468201d034 100644 --- a/modules/angular2/src/router/rules/regex_route_path.ts +++ b/modules/angular2/src/router/rules/route_paths/regex_route_path.ts @@ -1,5 +1,5 @@ import {RegExpWrapper, isBlank} from 'angular2/src/facade/lang'; -import {Url, RootUrl, serializeParams} from '../url_parser'; +import {Url, RootUrl, serializeParams} from '../../url_parser'; import {RoutePath, GeneratedUrl, MatchedUrl, UrlParams} from './route_path'; diff --git a/modules/angular2/src/router/rules/route_path.ts b/modules/angular2/src/router/rules/route_paths/route_path.ts similarity index 93% rename from modules/angular2/src/router/rules/route_path.ts rename to modules/angular2/src/router/rules/route_paths/route_path.ts index 5350f03314b3..37a4134c8a61 100644 --- a/modules/angular2/src/router/rules/route_path.ts +++ b/modules/angular2/src/router/rules/route_paths/route_path.ts @@ -1,4 +1,4 @@ -import {Url} from '../url_parser'; +import {Url} from '../../url_parser'; export interface UrlParams { [key: string]: any } diff --git a/modules/angular2/src/router/rules/rules.ts b/modules/angular2/src/router/rules/rules.ts index 2e6da86fab91..4b1479214a59 100644 --- a/modules/angular2/src/router/rules/rules.ts +++ b/modules/angular2/src/router/rules/rules.ts @@ -6,8 +6,8 @@ import {Map} from 'angular2/src/facade/collection'; import {RouteHandler} from './route_handlers/route_handler'; import {Url, serializeParams} from '../url_parser'; import {ComponentInstruction} from '../instruction'; -import {ParamRoutePath} from './param_route_path'; -import {GeneratedUrl, UrlParams} from './route_path'; +import {ParamRoutePath} from './route_paths/param_route_path'; +import {GeneratedUrl, UrlParams} from './route_paths/route_path'; // RouteMatch objects hold information about a match between a rule and a URL From d7946ffaba7ca033ebf5a8edcd30c489bdab16a7 Mon Sep 17 00:00:00 2001 From: Peter Bacon Darwin Date: Wed, 17 Feb 2016 15:06:59 +0000 Subject: [PATCH 27/43] refactor(router): move route_handlers into rules folder --- .../src/router/rules/route_handlers/async_route_handler.ts | 2 +- .../angular2/src/router/rules/route_handlers/route_handler.ts | 2 +- .../src/router/rules/route_handlers/sync_route_handler.ts | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/modules/angular2/src/router/rules/route_handlers/async_route_handler.ts b/modules/angular2/src/router/rules/route_handlers/async_route_handler.ts index 44cf0d3001fb..5c425afa30aa 100644 --- a/modules/angular2/src/router/rules/route_handlers/async_route_handler.ts +++ b/modules/angular2/src/router/rules/route_handlers/async_route_handler.ts @@ -1,7 +1,7 @@ import {isPresent, Type} from 'angular2/src/facade/lang'; import {RouteHandler} from './route_handler'; -import {RouteData, BLANK_ROUTE_DATA} from '../instruction'; +import {RouteData, BLANK_ROUTE_DATA} from '../../instruction'; export class AsyncRouteHandler implements RouteHandler { diff --git a/modules/angular2/src/router/rules/route_handlers/route_handler.ts b/modules/angular2/src/router/rules/route_handlers/route_handler.ts index d34ddad300fb..1c8dde841ad7 100644 --- a/modules/angular2/src/router/rules/route_handlers/route_handler.ts +++ b/modules/angular2/src/router/rules/route_handlers/route_handler.ts @@ -1,5 +1,5 @@ import {Type} from 'angular2/src/facade/lang'; -import {RouteData} from '../instruction'; +import {RouteData} from '../../instruction'; export interface RouteHandler { componentType: Type; diff --git a/modules/angular2/src/router/rules/route_handlers/sync_route_handler.ts b/modules/angular2/src/router/rules/route_handlers/sync_route_handler.ts index 198933d3ce0b..e06b5b57c85c 100644 --- a/modules/angular2/src/router/rules/route_handlers/sync_route_handler.ts +++ b/modules/angular2/src/router/rules/route_handlers/sync_route_handler.ts @@ -2,7 +2,7 @@ import {PromiseWrapper} from 'angular2/src/facade/async'; import {isPresent, Type} from 'angular2/src/facade/lang'; import {RouteHandler} from './route_handler'; -import {RouteData, BLANK_ROUTE_DATA} from '../instruction'; +import {RouteData, BLANK_ROUTE_DATA} from '../../instruction'; export class SyncRouteHandler implements RouteHandler { From 65015178ba795b5372e2d923103eababac63beb0 Mon Sep 17 00:00:00 2001 From: Peter Bacon Darwin Date: Wed, 17 Feb 2016 15:07:35 +0000 Subject: [PATCH 28/43] refactor(router): move directive tests into their own folder --- modules/angular2/test/router/directives/router_link_spec.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/angular2/test/router/directives/router_link_spec.ts b/modules/angular2/test/router/directives/router_link_spec.ts index cf20732deb36..e3563b2821db 100644 --- a/modules/angular2/test/router/directives/router_link_spec.ts +++ b/modules/angular2/test/router/directives/router_link_spec.ts @@ -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'; From 7fdf52c9b18d941ceb02ed99f15faf31252230f9 Mon Sep 17 00:00:00 2001 From: Peter Bacon Darwin Date: Wed, 17 Feb 2016 15:18:51 +0000 Subject: [PATCH 29/43] refactor(router): pass route_paths to rule constructors --- .../rules/route_paths/param_route_path.ts | 5 +++++ .../rules/route_paths/regex_route_path.ts | 4 ++++ .../router/rules/route_paths/route_path.ts | 1 + modules/angular2/src/router/rules/rule_set.ts | 20 +++++++++++++------ modules/angular2/src/router/rules/rules.ts | 18 ++++++++++------- 5 files changed, 35 insertions(+), 13 deletions(-) diff --git a/modules/angular2/src/router/rules/route_paths/param_route_path.ts b/modules/angular2/src/router/rules/route_paths/param_route_path.ts index a0d14bda9d1b..4555bea83b0f 100644 --- a/modules/angular2/src/router/rules/route_paths/param_route_path.ts +++ b/modules/angular2/src/router/rules/route_paths/param_route_path.ts @@ -191,6 +191,11 @@ export class ParamRoutePath implements RoutePath { 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. diff --git a/modules/angular2/src/router/rules/route_paths/regex_route_path.ts b/modules/angular2/src/router/rules/route_paths/regex_route_path.ts index bf468201d034..03f45e1b1d1e 100644 --- a/modules/angular2/src/router/rules/route_paths/regex_route_path.ts +++ b/modules/angular2/src/router/rules/route_paths/regex_route_path.ts @@ -35,4 +35,8 @@ export class RegexRoutePath implements RoutePath { } generateUrl(params: UrlParams): GeneratedUrl { return this._serializer(params); } + + toString() { + return this._reString; + } } \ No newline at end of file diff --git a/modules/angular2/src/router/rules/route_paths/route_path.ts b/modules/angular2/src/router/rules/route_paths/route_path.ts index 37a4134c8a61..2e594cd8cb8c 100644 --- a/modules/angular2/src/router/rules/route_paths/route_path.ts +++ b/modules/angular2/src/router/rules/route_paths/route_path.ts @@ -18,4 +18,5 @@ export interface RoutePath { hash: string; matchUrl(url: Url): MatchedUrl; generateUrl(params: UrlParams): GeneratedUrl; + toString(): string; } diff --git a/modules/angular2/src/router/rules/rule_set.ts b/modules/angular2/src/router/rules/rule_set.ts index 0e2f80368773..1b8ecce26085 100644 --- a/modules/angular2/src/router/rules/rule_set.ts +++ b/modules/angular2/src/router/rules/rule_set.ts @@ -11,8 +11,13 @@ import { 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 {ParamRoutePath} from './route_paths/param_route_path'; +import {RegexRoutePath} from './route_paths/regex_route_path'; + import {Url} from '../url_parser'; import {ComponentInstruction} from '../instruction'; @@ -53,7 +58,8 @@ export class RuleSet { if (config instanceof AuxRoute) { handler = new SyncRouteHandler(config.component, config.data); let path = config.path.startsWith('/') ? config.path.substring(1) : config.path; - let auxRule = new RouteRule(config.path, handler); + let routePath = new ParamRoutePath(path); + let auxRule = new RouteRule(routePath, handler); this.auxRulesByPath.set(path, auxRule); if (isPresent(config.name)) { this.auxRulesByName.set(config.name, auxRule); @@ -64,7 +70,8 @@ export class RuleSet { let useAsDefault = false; if (config instanceof Redirect) { - let redirector = new RedirectRule(config.path, config.redirectTo); + let routePath = new ParamRoutePath(config.path); + let redirector = new RedirectRule(routePath, config.redirectTo); this._assertNoHashCollision(redirector.hash, config.path); this.rules.push(redirector); return true; @@ -77,7 +84,8 @@ export class RuleSet { handler = new AsyncRouteHandler(config.loader, config.data); useAsDefault = isPresent(config.useAsDefault) && config.useAsDefault; } - let newRule = new RouteRule(config.path, handler); + let routePath = new ParamRoutePath(config.path); + let newRule = new RouteRule(routePath, handler); this._assertNoHashCollision(newRule.hash, config.path); @@ -97,10 +105,10 @@ export class RuleSet { private _assertNoHashCollision(hash: string, path) { - this.rules.forEach((matcher) => { - if (hash == matcher.hash) { + this.rules.forEach((rule) => { + if (hash == rule.hash) { throw new BaseException( - `Configuration '${path}' conflicts with existing route '${matcher.path}'`); + `Configuration '${path}' conflicts with existing route '${rule.path}'`); } }); } diff --git a/modules/angular2/src/router/rules/rules.ts b/modules/angular2/src/router/rules/rules.ts index 4b1479214a59..ade59aaf82dc 100644 --- a/modules/angular2/src/router/rules/rules.ts +++ b/modules/angular2/src/router/rules/rules.ts @@ -6,7 +6,7 @@ import {Map} from 'angular2/src/facade/collection'; import {RouteHandler} from './route_handlers/route_handler'; import {Url, serializeParams} from '../url_parser'; import {ComponentInstruction} from '../instruction'; -import {ParamRoutePath} from './route_paths/param_route_path'; +import {RoutePath} from './route_paths/route_path'; import {GeneratedUrl, UrlParams} from './route_paths/route_path'; @@ -33,14 +33,16 @@ export interface AbstractRule { } export class RedirectRule implements AbstractRule { - private _pathRecognizer: ParamRoutePath; public hash: string; - constructor(public path: string, public redirectTo: any[]) { - this._pathRecognizer = new ParamRoutePath(path); + constructor(private _pathRecognizer: RoutePath, public redirectTo: any[]) { this.hash = this._pathRecognizer.hash; } + get path() { + return this._pathRecognizer.toString(); + } + /** * Returns `null` or a `ParsedUrl` representing the new path to match */ @@ -65,17 +67,19 @@ export class RouteRule implements AbstractRule { hash: string; private _cache: Map = new Map(); - private _pathRecognizer: ParamRoutePath; // TODO: cache component instruction instances by params and by ParsedUrl instance - constructor(public path: string, public handler: RouteHandler) { - this._pathRecognizer = new ParamRoutePath(path); + constructor(private _pathRecognizer : RoutePath, public handler: RouteHandler) { this.specificity = this._pathRecognizer.specificity; this.hash = this._pathRecognizer.hash; this.terminal = this._pathRecognizer.terminal; } + get path() { + return this._pathRecognizer.toString(); + } + recognize(beginningSegment: Url): Promise { var res = this._pathRecognizer.matchUrl(beginningSegment); if (isBlank(res)) { From 3407f48e306c00fbf78fbb9935c0d858a470d774 Mon Sep 17 00:00:00 2001 From: Peter Bacon Darwin Date: Wed, 17 Feb 2016 15:43:32 +0000 Subject: [PATCH 30/43] refactor(router): remove unnecessary properties The issue indicated in the code was fixed in TypeScript 1.6 --- modules/angular2/src/router/route_config/route_config_impl.ts | 4 ---- 1 file changed, 4 deletions(-) diff --git a/modules/angular2/src/router/route_config/route_config_impl.ts b/modules/angular2/src/router/route_config/route_config_impl.ts index b766fd7a18d4..fed250943036 100644 --- a/modules/angular2/src/router/route_config/route_config_impl.ts +++ b/modules/angular2/src/router/route_config/route_config_impl.ts @@ -83,10 +83,6 @@ export class AuxRoute implements RouteDefinition { path: string; component: Type; name: string; - // added next three properties to work around https://github.com/Microsoft/TypeScript/issues/4107 - aux: string = null; - loader: Function = null; - redirectTo: any[] = null; useAsDefault: boolean = false; constructor({path, component, name}: {path: string, component: Type, name?: string}) { this.path = path; From 45416e3564ec4c035a3d39a1564bb22a42791ab8 Mon Sep 17 00:00:00 2001 From: Peter Bacon Darwin Date: Wed, 17 Feb 2016 15:45:06 +0000 Subject: [PATCH 31/43] style(router): move private method to bottom of class --- modules/angular2/src/router/rules/rule_set.ts | 20 +++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/modules/angular2/src/router/rules/rule_set.ts b/modules/angular2/src/router/rules/rule_set.ts index 1b8ecce26085..8d9d98e0921f 100644 --- a/modules/angular2/src/router/rules/rule_set.ts +++ b/modules/angular2/src/router/rules/rule_set.ts @@ -104,16 +104,6 @@ export class RuleSet { } - private _assertNoHashCollision(hash: string, path) { - this.rules.forEach((rule) => { - if (hash == rule.hash) { - throw new BaseException( - `Configuration '${path}' conflicts with existing route '${rule.path}'`); - } - }); - } - - /** * Given a URL, returns a list of `RouteMatch`es, which are partial recognitions for some route. */ @@ -170,4 +160,14 @@ export class RuleSet { } return pathRecognizer.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}'`); + } + }); + } + } From 138839c354cce26b1a5cb0ae1b6c4fc4aa33efe6 Mon Sep 17 00:00:00 2001 From: Peter Bacon Darwin Date: Wed, 17 Feb 2016 16:52:04 +0000 Subject: [PATCH 32/43] refactor(router): remove unnecessary properties The issue indicated in the code was fixed in TypeScript 1.6 --- modules/angular2/src/router/route_config/route_config_impl.ts | 4 ---- 1 file changed, 4 deletions(-) diff --git a/modules/angular2/src/router/route_config/route_config_impl.ts b/modules/angular2/src/router/route_config/route_config_impl.ts index fed250943036..c61f68484293 100644 --- a/modules/angular2/src/router/route_config/route_config_impl.ts +++ b/modules/angular2/src/router/route_config/route_config_impl.ts @@ -41,10 +41,6 @@ export class Route implements RouteDefinition { component: Type; name: string; useAsDefault: boolean; - // added next three properties to work around https://github.com/Microsoft/TypeScript/issues/4107 - aux: string = null; - loader: Function = null; - redirectTo: any[] = null; constructor({path, component, name, data, useAsDefault}: { path: string, component: Type, name?: string, data?: {[key: string]: any}, useAsDefault?: boolean From 404b4f411bc334a37fb3f4c51fba50a4b9132a14 Mon Sep 17 00:00:00 2001 From: Peter Bacon Darwin Date: Wed, 17 Feb 2016 17:05:53 +0000 Subject: [PATCH 33/43] feat(router): add support for regular expression route paths --- .../router/route_config/route_config_impl.ts | 18 +++++++-- .../angular2/src/router/route_definition.ts | 4 +- modules/angular2/src/router/rules/rule_set.ts | 30 ++++++++++++--- .../route_paths/regex_route_param_spec.ts | 9 +++++ .../test/router/rules/rule_set_spec.ts | 37 +++++++++++++++++++ 5 files changed, 87 insertions(+), 11 deletions(-) diff --git a/modules/angular2/src/router/route_config/route_config_impl.ts b/modules/angular2/src/router/route_config/route_config_impl.ts index c61f68484293..e2b1b5337370 100644 --- a/modules/angular2/src/router/route_config/route_config_impl.ts +++ b/modules/angular2/src/router/route_config/route_config_impl.ts @@ -1,5 +1,7 @@ import {CONST, Type, isPresent} from 'angular2/src/facade/lang'; import {RouteDefinition} from '../route_definition'; +import {RegexSerializer} from 'rules/route_paths/regex_route_path'; + export {RouteDefinition} from '../route_definition'; /** @@ -41,15 +43,25 @@ export class Route implements RouteDefinition { component: Type; name: string; useAsDefault: boolean; - constructor({path, component, name, data, useAsDefault}: { - path: string, - component: Type, name?: string, data?: {[key: string]: any}, useAsDefault?: boolean + regex: string; + serializer: RegexSerializer; + + constructor({path, component, name, data, useAsDefault, regex, serializer}: { + path?: string, + component: Type, + name?: string, + data?: {[key: string]: any}, + useAsDefault?: boolean, + regex?: string, + serializer?: RegexSerializer }) { this.path = path; this.component = component; this.name = name; this.data = data; this.useAsDefault = useAsDefault; + this.regex = regex; + this.serializer = serializer; } } diff --git a/modules/angular2/src/router/route_definition.ts b/modules/angular2/src/router/route_definition.ts index 376242625f27..d9fbc9ccb020 100644 --- a/modules/angular2/src/router/route_definition.ts +++ b/modules/angular2/src/router/route_definition.ts @@ -1,4 +1,5 @@ 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. @@ -15,8 +16,7 @@ export interface RouteDefinition { path?: string; aux?: string; regex?: string; - // TODO: - // serializer?: + serializer?: RegexSerializer; component?: Type | ComponentDefinition; loader?: Function; redirectTo?: any[]; diff --git a/modules/angular2/src/router/rules/rule_set.ts b/modules/angular2/src/router/rules/rule_set.ts index 8d9d98e0921f..d8378d9bb704 100644 --- a/modules/angular2/src/router/rules/rule_set.ts +++ b/modules/angular2/src/router/rules/rule_set.ts @@ -1,4 +1,4 @@ -import {isBlank, isPresent} from 'angular2/src/facade/lang'; +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'; @@ -15,6 +15,7 @@ import { 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'; @@ -57,10 +58,9 @@ export class RuleSet { if (config instanceof AuxRoute) { handler = new SyncRouteHandler(config.component, config.data); - let path = config.path.startsWith('/') ? config.path.substring(1) : config.path; - let routePath = new ParamRoutePath(path); + let routePath = this._getRoutePath(config); let auxRule = new RouteRule(routePath, handler); - this.auxRulesByPath.set(path, auxRule); + this.auxRulesByPath.set(routePath.toString(), auxRule); if (isPresent(config.name)) { this.auxRulesByName.set(config.name, auxRule); } @@ -70,7 +70,7 @@ export class RuleSet { let useAsDefault = false; if (config instanceof Redirect) { - let routePath = new ParamRoutePath(config.path); + let routePath = this._getRoutePath(config); let redirector = new RedirectRule(routePath, config.redirectTo); this._assertNoHashCollision(redirector.hash, config.path); this.rules.push(redirector); @@ -84,7 +84,7 @@ export class RuleSet { handler = new AsyncRouteHandler(config.loader, config.data); useAsDefault = isPresent(config.useAsDefault) && config.useAsDefault; } - let routePath = new ParamRoutePath(config.path); + let routePath = this._getRoutePath(config); let newRule = new RouteRule(routePath, handler); this._assertNoHashCollision(newRule.hash, config.path); @@ -170,4 +170,22 @@ export class RuleSet { }); } + private _getRoutePath(config : RouteDefinition) : RoutePath { + if (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 (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'); + } + } diff --git a/modules/angular2/test/router/rules/route_paths/regex_route_param_spec.ts b/modules/angular2/test/router/rules/route_paths/regex_route_param_spec.ts index 2cb5fb98b9dc..19819d9c60a2 100644 --- a/modules/angular2/test/router/rules/route_paths/regex_route_param_spec.ts +++ b/modules/angular2/test/router/rules/route_paths/regex_route_param_spec.ts @@ -36,6 +36,15 @@ export function main() { 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 url = rec.generateUrl({a: 'one', b: 'two'}); + expect(url.urlPath).toEqual('/a/one/b/two'); + }); + function emptySerializer(params) { return new GeneratedUrl('', []); } }); } diff --git a/modules/angular2/test/router/rules/rule_set_spec.ts b/modules/angular2/test/router/rules/rule_set_spec.ts index c1106d266e04..8be8c9a03a4d 100644 --- a/modules/angular2/test/router/rules/rule_set_spec.ts +++ b/modules/angular2/test/router/rules/rule_set_spec.ts @@ -14,6 +14,7 @@ import {Map, StringMapWrapper} from 'angular2/src/facade/collection'; 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/route_config_decorator'; import {parser} from 'angular2/src/router/url_parser'; @@ -72,6 +73,25 @@ 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 +143,23 @@ export function main() { }); + it('should generate using a serializer', () => { + function simpleSerializer(params): GeneratedUrl { + return new GeneratedUrl(`/${params.a}/${params.b}`, {c: params.c}); + } + + recognizer.config(new Route({ + name: 'Route1', + regex: '^(.+)/(.+)$', + serializer: simpleSerializer, + component: DummyCmpA + })); + var result = recognizer.generate('Route1', { a: 'first', b:'second', c:'third'}); + 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', {})) From 17fee3d46ab0d61ceff1f215536319cb9abf7249 Mon Sep 17 00:00:00 2001 From: Peter Bacon Darwin Date: Wed, 24 Feb 2016 14:45:19 +0000 Subject: [PATCH 34/43] refactor(router): rename route "...Recognizer" classes to "...Rule" --- modules/angular2/src/router/rules/rule_set.ts | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/modules/angular2/src/router/rules/rule_set.ts b/modules/angular2/src/router/rules/rule_set.ts index d8378d9bb704..1407a236a59a 100644 --- a/modules/angular2/src/router/rules/rule_set.ts +++ b/modules/angular2/src/router/rules/rule_set.ts @@ -146,19 +146,19 @@ export class RuleSet { } generate(name: string, params: any): ComponentInstruction { - var pathRecognizer: RouteRule = this.rulesByName.get(name); - if (isBlank(pathRecognizer)) { + var rule: RouteRule = this.rulesByName.get(name); + if (isBlank(rule)) { return null; } - return pathRecognizer.generate(params); + return rule.generate(params); } generateAuxiliary(name: string, params: any): ComponentInstruction { - var pathRecognizer: RouteRule = this.auxRulesByName.get(name); - if (isBlank(pathRecognizer)) { + var rule: RouteRule = this.auxRulesByName.get(name); + if (isBlank(rule)) { return null; } - return pathRecognizer.generate(params); + return rule.generate(params); } private _assertNoHashCollision(hash: string, path) { From 5b5f613b6c4cf010119c8a6223d7b57d500fd46d Mon Sep 17 00:00:00 2001 From: Peter Bacon Darwin Date: Wed, 24 Feb 2016 14:46:35 +0000 Subject: [PATCH 35/43] refactor(router): change `Recognizer`s -> `PathRoute` and associated changes --- modules/angular2/src/router/rules/rules.ts | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/modules/angular2/src/router/rules/rules.ts b/modules/angular2/src/router/rules/rules.ts index ade59aaf82dc..6bbf13ebe697 100644 --- a/modules/angular2/src/router/rules/rules.ts +++ b/modules/angular2/src/router/rules/rules.ts @@ -70,18 +70,18 @@ export class RouteRule implements AbstractRule { // TODO: cache component instruction instances by params and by ParsedUrl instance - constructor(private _pathRecognizer : RoutePath, public handler: RouteHandler) { - this.specificity = this._pathRecognizer.specificity; - this.hash = this._pathRecognizer.hash; - this.terminal = this._pathRecognizer.terminal; + constructor(private _routePath : RoutePath, public handler: RouteHandler) { + this.specificity = this._routePath.specificity; + this.hash = this._routePath.hash; + this.terminal = this._routePath.terminal; } get path() { - return this._pathRecognizer.toString(); + return this._routePath.toString(); } recognize(beginningSegment: Url): Promise { - var res = this._pathRecognizer.matchUrl(beginningSegment); + var res = this._routePath.matchUrl(beginningSegment); if (isBlank(res)) { return null; } @@ -93,14 +93,14 @@ export class RouteRule implements AbstractRule { } generate(params: {[key: string]: any}): ComponentInstruction { - var generated = this._pathRecognizer.generateUrl(params); + var generated = this._routePath.generateUrl(params); var urlPath = generated.urlPath; var urlParams = generated.urlParams; return this._getInstruction(urlPath, urlParams, params); } generateComponentPathValues(params: {[key: string]: any}): GeneratedUrl { - return this._pathRecognizer.generateUrl(params); + return this._routePath.generateUrl(params); } private _getInstruction(urlPath: string, urlParams: UrlParams, From 0a50039c6addaec95d3daec1946218e86783fd16 Mon Sep 17 00:00:00 2001 From: Peter Bacon Darwin Date: Wed, 24 Feb 2016 18:50:27 +0000 Subject: [PATCH 36/43] refactor(router): make UrlParams more explicit --- .../test/integration/lifecycle_hook_spec.js | 2 +- modules/angular2/src/router/route_registry.ts | 41 ++++++++----- .../rules/route_paths/param_route_path.ts | 31 +++++----- .../rules/route_paths/regex_route_path.ts | 6 +- .../router/rules/route_paths/route_path.ts | 4 +- modules/angular2/src/router/rules/rules.ts | 18 +++--- modules/angular2/src/router/url_parser.ts | 58 +++++++++++-------- .../route_paths/param_route_path_spec.ts | 14 ++--- .../route_paths/regex_route_param_spec.ts | 8 +-- .../test/router/rules/rule_set_spec.ts | 5 +- 10 files changed, 100 insertions(+), 87 deletions(-) diff --git a/modules/angular1_router/test/integration/lifecycle_hook_spec.js b/modules/angular1_router/test/integration/lifecycle_hook_spec.js index de9923cc1c78..ec49c9d56363 100644 --- a/modules/angular1_router/test/integration/lifecycle_hook_spec.js +++ b/modules/angular1_router/test/integration/lifecycle_hook_spec.js @@ -351,7 +351,7 @@ describe('Navigation lifecycle', function () { expect(spy).toHaveBeenCalled(); 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); })); diff --git a/modules/angular2/src/router/route_registry.ts b/modules/angular2/src/router/route_registry.ts index 07234c31dd26..5bb7750dde11 100644 --- a/modules/angular2/src/router/route_registry.ts +++ b/modules/angular2/src/router/route_registry.ts @@ -36,11 +36,19 @@ import { } from './instruction'; import {normalizeRouteConfig, assertComponentExists} from './route_config/route_config_nomalizer'; -import {parser, Url, pathSegmentsToUrl, serializeParams} from './url_parser'; +import {parser, Url, UrlParams, pathSegmentsToUrl} from './url_parser'; 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 | {[key: string]: any}; +export type LinkItem = LinkRouteItem | Array; +export type LinkItemArray = Array; /** * Token used to bind the component with the top-level {@link RouteConfig}s for the @@ -235,7 +243,7 @@ export class RouteRegistry { * If the optional param `_aux` is `true`, then we generate starting at an auxiliary * route boundary. */ - generate(linkParams: any[], ancestorInstructions: Instruction[], _aux = false): Instruction { + generate(linkParams: LinkItemArray, ancestorInstructions: Instruction[], _aux = false): Instruction { var params = splitAndFlattenLinkParams(linkParams); var prevInstruction; @@ -263,7 +271,7 @@ export class RouteRegistry { // we're on to implicit child/sibling route } else { // we must only peak at the link param, and not consume it - let routeName = ListWrapper.first(params); + let routeName = ListWrapper.first(params) as string; let parentComponentType = this._rootComponent; let grandparentComponentType = null; @@ -365,7 +373,7 @@ export class RouteRegistry { } let linkParamIndex = 0; - let routeParams = {}; + let routeParams = new UrlParams(); // first, recognize the primary route if one is provided if (linkParamIndex < linkParams.length && isString(linkParams[linkParamIndex])) { @@ -377,7 +385,7 @@ export class RouteRegistry { if (linkParamIndex < linkParams.length) { let linkParam = linkParams[linkParamIndex]; if (isStringMap(linkParam) && !isArray(linkParam)) { - routeParams = linkParam; + routeParams = new UrlParams(linkParam); linkParamIndex += 1; } } @@ -398,7 +406,7 @@ export class RouteRegistry { return this._generate(linkParams, ancestorInstructions, prevInstruction, _aux, _originalLink); }); - }, generatedUrl.urlPath, serializeParams(generatedUrl.urlParams)); + }, generatedUrl.urlPath, generatedUrl.urlParams.toArray()); } componentInstruction = _aux ? rules.generateAuxiliary(routeName, routeParams) : @@ -459,7 +467,7 @@ export class RouteRegistry { var defaultChild = null; if (isPresent(rules.defaultRule.handler.componentType)) { - var componentInstruction = rules.defaultRule.generate({}); + var componentInstruction = rules.defaultRule.generate(new UrlParams()); if (!rules.defaultRule.terminal) { defaultChild = this.generateDefault(rules.defaultRule.handler.componentType); } @@ -477,17 +485,20 @@ export class RouteRegistry { * Given: ['/a/b', {c: 2}] * Returns: ['', 'a', 'b', {c: 2}] */ -function splitAndFlattenLinkParams(linkParams: any[]): any[] { - return linkParams.reduce((accumulation: any[], item) => { +function splitAndFlattenLinkParams(linkParams) { + var accumulation = []; + linkParams.forEach(function (item) { if (isString(item)) { - let strItem: string = item; - return accumulation.concat(strItem.split('/')); + var strItem = item; + 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 */ diff --git a/modules/angular2/src/router/rules/route_paths/param_route_path.ts b/modules/angular2/src/router/rules/route_paths/param_route_path.ts index 4555bea83b0f..84472c49ee6c 100644 --- a/modules/angular2/src/router/rules/route_paths/param_route_path.ts +++ b/modules/angular2/src/router/rules/route_paths/param_route_path.ts @@ -3,8 +3,8 @@ import {BaseException} from 'angular2/src/facade/exceptions'; import {StringMapWrapper} from 'angular2/src/facade/collection'; import {TouchMap, normalizeString} from '../../utils'; -import {Url, RootUrl, serializeParams} from '../../url_parser'; -import {RoutePath, GeneratedUrl, MatchedUrl, UrlParams} from './route_path'; +import {Url, RootUrl, UrlParams} from '../../url_parser'; +import {RoutePath, GeneratedUrl, MatchedUrl} from './route_path'; @@ -147,28 +147,23 @@ export class ParamRoutePath implements RoutePath { var urlPath = captured.join('/'); - var auxiliary; - var urlParams; - var allParams; + 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; - allParams = isPresent(paramsSegment.params) ? - StringMapWrapper.merge(paramsSegment.params, positionalParams) : - positionalParams; - - urlParams = serializeParams(paramsSegment.params); - - + if (isPresent(paramsSegment.params)) { + allParams = StringMapWrapper.merge(paramsSegment.params, positionalParams); + urlParams = paramsSegment.params.toArray(); + } else { + allParams = positionalParams; + } auxiliary = currentUrlSegment.auxiliary; - } else { - allParams = positionalParams; - auxiliary = []; - urlParams = []; } - return new MatchedUrl(urlPath, urlParams, allParams, auxiliary, nextUrlSegment); + return new MatchedUrl(urlPath, urlParams, new UrlParams(allParams), auxiliary, nextUrlSegment); } @@ -186,7 +181,7 @@ export class ParamRoutePath implements RoutePath { var urlPath = path.join('/'); var nonPositionalParams = paramTokens.getUnused(); - var urlParams = nonPositionalParams; + var urlParams = new UrlParams(nonPositionalParams); return new GeneratedUrl(urlPath, urlParams); } diff --git a/modules/angular2/src/router/rules/route_paths/regex_route_path.ts b/modules/angular2/src/router/rules/route_paths/regex_route_path.ts index 03f45e1b1d1e..8fc1fa1ed2e1 100644 --- a/modules/angular2/src/router/rules/route_paths/regex_route_path.ts +++ b/modules/angular2/src/router/rules/route_paths/regex_route_path.ts @@ -1,6 +1,6 @@ import {RegExpWrapper, isBlank} from 'angular2/src/facade/lang'; -import {Url, RootUrl, serializeParams} from '../../url_parser'; -import {RoutePath, GeneratedUrl, MatchedUrl, UrlParams} from './route_path'; +import {Url, RootUrl, UrlParams} from '../../url_parser'; +import {RoutePath, GeneratedUrl, MatchedUrl} from './route_path'; export interface RegexSerializer { (params: UrlParams): GeneratedUrl } @@ -25,7 +25,7 @@ export class RegexRoutePath implements RoutePath { return null; } - var params: UrlParams = {}; + var params: UrlParams = new UrlParams(); for (let i = 0; i < match.length; i += 1) { params[i.toString()] = match[i]; diff --git a/modules/angular2/src/router/rules/route_paths/route_path.ts b/modules/angular2/src/router/rules/route_paths/route_path.ts index 2e594cd8cb8c..4a6ea1e2470b 100644 --- a/modules/angular2/src/router/rules/route_paths/route_path.ts +++ b/modules/angular2/src/router/rules/route_paths/route_path.ts @@ -1,6 +1,4 @@ -import {Url} from '../../url_parser'; - -export interface UrlParams { [key: string]: any } +import {Url, UrlParams} from '../../url_parser'; export class MatchedUrl { constructor(public urlPath: string, public urlParams: string[], public allParams: UrlParams, diff --git a/modules/angular2/src/router/rules/rules.ts b/modules/angular2/src/router/rules/rules.ts index 6bbf13ebe697..75e5eb0b87e4 100644 --- a/modules/angular2/src/router/rules/rules.ts +++ b/modules/angular2/src/router/rules/rules.ts @@ -4,10 +4,10 @@ import {PromiseWrapper} from 'angular2/src/facade/promise'; import {Map} from 'angular2/src/facade/collection'; import {RouteHandler} from './route_handlers/route_handler'; -import {Url, serializeParams} from '../url_parser'; +import {Url, UrlParams} from '../url_parser'; import {ComponentInstruction} from '../instruction'; import {RoutePath} from './route_paths/route_path'; -import {GeneratedUrl, UrlParams} 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 @@ -92,29 +92,27 @@ export class RouteRule implements AbstractRule { }); } - generate(params: {[key: string]: any}): ComponentInstruction { + generate(params: UrlParams): ComponentInstruction { var generated = this._routePath.generateUrl(params); var urlPath = generated.urlPath; var urlParams = generated.urlParams; - return this._getInstruction(urlPath, urlParams, params); + return this._getInstruction(urlPath, urlParams.toArray(), params); } - generateComponentPathValues(params: {[key: string]: any}): GeneratedUrl { + generateComponentPathValues(params: UrlParams): GeneratedUrl { return this._routePath.generateUrl(params); } - private _getInstruction(urlPath: string, urlParams: UrlParams, + private _getInstruction(urlPath: string, urlParams: string[], params: {[key: string]: any}): ComponentInstruction { if (isBlank(this.handler.componentType)) { throw new BaseException(`Tried to get instruction before the type was loaded.`); } - var serializedParams = serializeParams(urlParams); - - var hashKey = urlPath + '?' + serializedParams.join('?'); + var hashKey = urlPath + '?' + urlParams.join('&'); if (this._cache.has(hashKey)) { return this._cache.get(hashKey); } - var instruction = new ComponentInstruction(urlPath, serializedParams, this.handler.data, + var instruction = new ComponentInstruction(urlPath, urlParams, this.handler.data, this.handler.componentType, this.terminal, this.specificity, params); this._cache.set(hashKey, instruction); diff --git a/modules/angular2/src/router/url_parser.ts b/modules/angular2/src/router/url_parser.ts index 2726dc1e37fa..2a6bdf4848df 100644 --- a/modules/angular2/src/router/url_parser.ts +++ b/modules/angular2/src/router/url_parser.ts @@ -2,13 +2,37 @@ import {StringMapWrapper} from 'angular2/src/facade/collection'; import {isPresent, isBlank, RegExpWrapper, CONST_EXPR} from 'angular2/src/facade/lang'; import {BaseException, WrappedException} from 'angular2/src/facade/exceptions'; +export class UrlParams { + [key: string]: any + + constructor(params : {[key: string]: any} = {}) { + if (isPresent(params)) { + StringMapWrapper.forEach(params, (value, key) => { + this[key] = value; + }); + } + } + + toArray() : string[] { + var params = []; + StringMapWrapper.forEach(this, (value, key) => { + if (value === true) { + params.push(key); + } else { + params.push(key + '=' + value); + } + }); + return params; + } +} + /** * This class represents a parsed URL */ export class Url { constructor(public path: string, public child: Url = null, public auxiliary: Url[] = CONST_EXPR([]), - public params: {[key: string]: any} = null) {} + public params: UrlParams = new UrlParams()) {} toString(): string { return this.path + this._matrixParamsToString() + this._auxToString() + this._childString(); @@ -28,7 +52,7 @@ export class Url { return ''; } - return ';' + serializeParams(this.params).join(';'); + return ';' + this.params.toArray().join(';'); } /** @internal */ @@ -37,7 +61,7 @@ export class Url { export class RootUrl extends Url { constructor(path: string, child: Url = null, auxiliary: Url[] = CONST_EXPR([]), - params: {[key: string]: any} = null) { + params: UrlParams = null) { super(path, child, auxiliary, params); } @@ -52,7 +76,7 @@ export class RootUrl extends Url { return ''; } - return '?' + serializeParams(this.params).join('&'); + return '?' + this.params.toArray().join('&'); } } @@ -145,8 +169,8 @@ export class UrlParser { return new Url(path, child, aux, matrixParams); } - parseQueryParams(): {[key: string]: any} { - var params = {}; + parseQueryParams(): UrlParams { + var params = new UrlParams(); this.capture('?'); this.parseParam(params); while (this._remaining.length > 0 && this.peekStartsWith('&')) { @@ -156,8 +180,8 @@ export class UrlParser { return params; } - parseMatrixParams(): {[key: string]: any} { - var params = {}; + parseMatrixParams(): UrlParams { + var params = new UrlParams(); while (this._remaining.length > 0 && this.peekStartsWith(';')) { this.capture(';'); this.parseParam(params); @@ -165,7 +189,7 @@ export class UrlParser { return params; } - parseParam(params: {[key: string]: any}): void { + parseParam(params: UrlParams): void { var key = matchUrlSegment(this._remaining); if (isBlank(key)) { return; @@ -200,18 +224,4 @@ export class 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; -} +export var parser = new UrlParser(); \ No newline at end of file diff --git a/modules/angular2/test/router/rules/route_paths/param_route_path_spec.ts b/modules/angular2/test/router/rules/route_paths/param_route_path_spec.ts index 09031d4707ac..1456c82be1d4 100644 --- a/modules/angular2/test/router/rules/route_paths/param_route_path_spec.ts +++ b/modules/angular2/test/router/rules/route_paths/param_route_path_spec.ts @@ -11,7 +11,7 @@ import { } from 'angular2/testing_internal'; import {ParamRoutePath} from 'angular2/src/router/rules/route_paths/param_route_path'; -import {parser, Url} from 'angular2/src/router/url_parser'; +import {parser, Url, UrlParams} from 'angular2/src/router/url_parser'; export function main() { describe('PathRecognizer', () => { @@ -53,14 +53,14 @@ export function main() { describe('matrix params', () => { it('should be parsed along with dynamic paths', () => { 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, new UrlParams({'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 ParamRoutePath('/person'); - var url = new Url('person', null, null, {'name': 'dave'}); + var url = new Url('person', null, null, new UrlParams({'name': 'dave'})); var match = rec.matchUrl(url); expect(match.allParams).toEqual({'name': 'dave'}); }); @@ -74,7 +74,7 @@ export function main() { it('should set matrix param values to true when no value is present', () => { 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, new UrlParams({'one': true, 'two': true, 'three': '3'})); var match = rec.matchUrl(url); expect(match.allParams).toEqual({'one': true, 'two': true, 'three': '3'}); }); @@ -82,9 +82,9 @@ export function main() { it('should be parsed on the final segment of the path', () => { 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 three = new Url('three', null, null, new UrlParams({'c': '3'})); + var two = new Url('two', three, null, new UrlParams({'b': '2'})); + var one = new Url('one', two, null, new UrlParams({'a': '1'})); var match = rec.matchUrl(one); expect(match.allParams).toEqual({'c': '3'}); diff --git a/modules/angular2/test/router/rules/route_paths/regex_route_param_spec.ts b/modules/angular2/test/router/rules/route_paths/regex_route_param_spec.ts index 19819d9c60a2..855f04aef3af 100644 --- a/modules/angular2/test/router/rules/route_paths/regex_route_param_spec.ts +++ b/modules/angular2/test/router/rules/route_paths/regex_route_param_spec.ts @@ -12,7 +12,7 @@ import { 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'; +import {parser, Url, UrlParams} from 'angular2/src/router/url_parser'; export function main() { describe('RegexRoutePath', () => { @@ -38,13 +38,13 @@ export function main() { it('should generate a url by calling the provided serializer', () => { function serializer(params) { - return new GeneratedUrl(`/a/${params.a}/b/${params.b}`, {}); + return new GeneratedUrl(`/a/${params.a}/b/${params.b}`, new UrlParams()); } var rec = new RegexRoutePath('/a/(.+)/b/(.+)$', serializer); - var url = rec.generateUrl({a: 'one', b: 'two'}); + var url = rec.generateUrl(new UrlParams({a: 'one', b: 'two'})); expect(url.urlPath).toEqual('/a/one/b/two'); }); - function emptySerializer(params) { return new GeneratedUrl('', []); } + function emptySerializer(params) { return new GeneratedUrl('', new UrlParams()); } }); } diff --git a/modules/angular2/test/router/rules/rule_set_spec.ts b/modules/angular2/test/router/rules/rule_set_spec.ts index 8be8c9a03a4d..7191ce7b4ac4 100644 --- a/modules/angular2/test/router/rules/rule_set_spec.ts +++ b/modules/angular2/test/router/rules/rule_set_spec.ts @@ -15,6 +15,7 @@ import {Map, StringMapWrapper} from 'angular2/src/facade/collection'; 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 {UrlParams} from 'angular2/src/router/url_parser'; import {Route, Redirect} from 'angular2/src/router/route_config/route_config_decorator'; import {parser} from 'angular2/src/router/url_parser'; @@ -75,7 +76,7 @@ export function main() { it('should recognize a regex', inject([AsyncTestCompleter], (async) => { function emptySerializer(params): GeneratedUrl { - return new GeneratedUrl('', {}); + return new GeneratedUrl('', new UrlParams()); } recognizer.config(new Route({ @@ -145,7 +146,7 @@ export function main() { it('should generate using a serializer', () => { function simpleSerializer(params): GeneratedUrl { - return new GeneratedUrl(`/${params.a}/${params.b}`, {c: params.c}); + return new GeneratedUrl(`/${params.a}/${params.b}`, new UrlParams({c: params.c})); } recognizer.config(new Route({ From cf5469af23440bdf1fd02c843ebf98873f07f91c Mon Sep 17 00:00:00 2001 From: Peter Bacon Darwin Date: Thu, 25 Feb 2016 21:34:27 +0000 Subject: [PATCH 37/43] refactor(router): fix un-dartable code --- .../router/route_config/route_config_impl.ts | 94 ++++++++----------- ...izer.dart => route_config_normalizer.dart} | 4 +- ...omalizer.ts => route_config_normalizer.ts} | 0 .../angular2/src/router/route_definition.dart | 4 +- modules/angular2/src/router/route_registry.ts | 28 +++--- .../rules/route_paths/param_route_path.ts | 16 ++-- .../rules/route_paths/regex_route_path.ts | 16 ++-- .../router/rules/route_paths/route_path.ts | 8 +- modules/angular2/src/router/rules/rule_set.ts | 4 +- modules/angular2/src/router/rules/rules.ts | 14 ++- modules/angular2/src/router/url_parser.ts | 57 +++++------ .../route_paths/param_route_path_spec.ts | 16 ++-- .../route_paths/regex_route_param_spec.ts | 11 ++- .../test/router/rules/rule_set_spec.ts | 9 +- .../angular2/test/router/url_parser_spec.ts | 2 +- 15 files changed, 134 insertions(+), 149 deletions(-) rename modules/angular2/src/router/route_config/{route_config_nomalizer.dart => route_config_normalizer.dart} (88%) rename modules/angular2/src/router/route_config/{route_config_nomalizer.ts => route_config_normalizer.ts} (100%) diff --git a/modules/angular2/src/router/route_config/route_config_impl.ts b/modules/angular2/src/router/route_config/route_config_impl.ts index e2b1b5337370..a81c0cf6ba48 100644 --- a/modules/angular2/src/router/route_config/route_config_impl.ts +++ b/modules/angular2/src/router/route_config/route_config_impl.ts @@ -1,6 +1,6 @@ import {CONST, Type, isPresent} from 'angular2/src/facade/lang'; import {RouteDefinition} from '../route_definition'; -import {RegexSerializer} from 'rules/route_paths/regex_route_path'; +import {RegexSerializer} from '../rules/route_paths/regex_route_path'; export {RouteDefinition} from '../route_definition'; @@ -14,6 +14,25 @@ export class RouteConfig { 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. * @@ -37,31 +56,13 @@ export class RouteConfig { * ``` */ @CONST() -export class Route implements RouteDefinition { - data: {[key: string]: any}; - path: string; - component: Type; - name: string; - useAsDefault: boolean; - regex: string; - serializer: RegexSerializer; +export class Route extends AbstractRoute { + component: any; + aux: string = null; - constructor({path, component, name, data, useAsDefault, regex, serializer}: { - path?: string, - component: Type, - name?: string, - data?: {[key: string]: any}, - useAsDefault?: boolean, - regex?: string, - serializer?: RegexSerializer - }) { - this.path = path; + constructor({name, useAsDefault, path, regex, serializer, data, component}: RouteDefinition) { + super({name: name, useAsDefault: useAsDefault, path: path, regex: regex, serializer: serializer, data: data}); this.component = component; - this.name = name; - this.data = data; - this.useAsDefault = useAsDefault; - this.regex = regex; - this.serializer = serializer; } } @@ -86,16 +87,12 @@ export class Route implements RouteDefinition { * ``` */ @CONST() -export class AuxRoute implements RouteDefinition { - data: {[key: string]: any} = null; - path: string; - component: Type; - name: string; - useAsDefault: boolean = false; - constructor({path, component, name}: {path: string, component: Type, name?: string}) { - this.path = path; +export class AuxRoute extends AbstractRoute { + component: any; + + constructor({name, useAsDefault, path, regex, serializer, data, component}: RouteDefinition) { + super({name: name, useAsDefault: useAsDefault, path: path, regex: regex, serializer: serializer, data: data}); this.component = component; - this.name = name; } } @@ -124,22 +121,13 @@ export class AuxRoute implements RouteDefinition { * ``` */ @CONST() -export class AsyncRoute implements RouteDefinition { - data: {[key: string]: any}; - path: string; +export class AsyncRoute extends AbstractRoute { loader: Function; - name: string; - useAsDefault: boolean; aux: string = null; - constructor({path, loader, name, data, useAsDefault}: { - path: string, - loader: Function, name?: string, data?: {[key: string]: any}, useAsDefault?: boolean - }) { - this.path = path; + + constructor({name, useAsDefault, path, regex, serializer, data, loader}: RouteDefinition) { + super({name: name, useAsDefault: useAsDefault, path: path, regex: regex, serializer: serializer, data: data}); this.loader = loader; - this.name = name; - this.data = data; - this.useAsDefault = useAsDefault; } } @@ -165,17 +153,11 @@ export class AsyncRoute implements RouteDefinition { * ``` */ @CONST() -export class Redirect implements RouteDefinition { - path: string; +export class Redirect extends AbstractRoute { redirectTo: any[]; - name: string = null; - // added next three properties to work around https://github.com/Microsoft/TypeScript/issues/4107 - loader: Function = null; - data: any = null; - aux: string = null; - useAsDefault: boolean = false; - constructor({path, redirectTo}: {path: string, redirectTo: any[]}) { - this.path = path; + + constructor({name, useAsDefault, path, regex, serializer, data, redirectTo}: RouteDefinition) { + super({name: name, useAsDefault: useAsDefault, path: path, regex: regex, serializer: serializer, data: data}); this.redirectTo = redirectTo; } } diff --git a/modules/angular2/src/router/route_config/route_config_nomalizer.dart b/modules/angular2/src/router/route_config/route_config_normalizer.dart similarity index 88% rename from modules/angular2/src/router/route_config/route_config_nomalizer.dart rename to modules/angular2/src/router/route_config/route_config_normalizer.dart index 6fe053e62d3b..60bc1516d0ea 100644 --- a/modules/angular2/src/router/route_config/route_config_nomalizer.dart +++ b/modules/angular2/src/router/route_config/route_config_normalizer.dart @@ -1,7 +1,9 @@ library angular2.src.router.route_config_normalizer; 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; RouteDefinition normalizeRouteConfig(RouteDefinition config, RouteRegistry registry) { diff --git a/modules/angular2/src/router/route_config/route_config_nomalizer.ts b/modules/angular2/src/router/route_config/route_config_normalizer.ts similarity index 100% rename from modules/angular2/src/router/route_config/route_config_nomalizer.ts rename to modules/angular2/src/router/route_config/route_config_normalizer.ts diff --git a/modules/angular2/src/router/route_definition.dart b/modules/angular2/src/router/route_definition.dart index 79c8b5672b64..2aa3f50894ad 100644 --- a/modules/angular2/src/router/route_definition.dart +++ b/modules/angular2/src/router/route_definition.dart @@ -4,5 +4,7 @@ abstract class RouteDefinition { final String path; final String name; 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}); } diff --git a/modules/angular2/src/router/route_registry.ts b/modules/angular2/src/router/route_registry.ts index 5bb7750dde11..21ca939ed912 100644 --- a/modules/angular2/src/router/route_registry.ts +++ b/modules/angular2/src/router/route_registry.ts @@ -35,8 +35,8 @@ import { DefaultInstruction } from './instruction'; -import {normalizeRouteConfig, assertComponentExists} from './route_config/route_config_nomalizer'; -import {parser, Url, UrlParams, pathSegmentsToUrl} from './url_parser'; +import {normalizeRouteConfig, assertComponentExists} from './route_config/route_config_normalizer'; +import {parser, Url, convertUrlParamsToArray, pathSegmentsToUrl} from './url_parser'; var _resolveToNull = PromiseWrapper.resolve(null); @@ -46,9 +46,9 @@ var _resolveToNull = PromiseWrapper.resolve(null); // - the next items are: // - an object containing parameters // - or an array describing an aux route -export type LinkRouteItem = string | {[key: string]: any}; -export type LinkItem = LinkRouteItem | Array; -export type LinkItemArray = Array; +// export type LinkRouteItem = string | Object; +// export type LinkItem = LinkRouteItem | Array; +// export type LinkItemArray = Array; /** * Token used to bind the component with the top-level {@link RouteConfig}s for the @@ -243,7 +243,7 @@ export class RouteRegistry { * If the optional param `_aux` is `true`, then we generate starting at an auxiliary * route boundary. */ - generate(linkParams: LinkItemArray, ancestorInstructions: Instruction[], _aux = false): Instruction { + generate(linkParams: any[], ancestorInstructions: Instruction[], _aux = false): Instruction { var params = splitAndFlattenLinkParams(linkParams); var prevInstruction; @@ -271,7 +271,7 @@ export class RouteRegistry { // we're on to implicit child/sibling route } else { // we must only peak at the link param, and not consume it - let routeName = ListWrapper.first(params) as string; + let routeName = ListWrapper.first(params); let parentComponentType = this._rootComponent; let grandparentComponentType = null; @@ -373,7 +373,7 @@ export class RouteRegistry { } let linkParamIndex = 0; - let routeParams = new UrlParams(); + let routeParams : {[key: string]: any} = {}; // first, recognize the primary route if one is provided if (linkParamIndex < linkParams.length && isString(linkParams[linkParamIndex])) { @@ -385,7 +385,7 @@ export class RouteRegistry { if (linkParamIndex < linkParams.length) { let linkParam = linkParams[linkParamIndex]; if (isStringMap(linkParam) && !isArray(linkParam)) { - routeParams = new UrlParams(linkParam); + routeParams = linkParam; linkParamIndex += 1; } } @@ -406,7 +406,7 @@ export class RouteRegistry { return this._generate(linkParams, ancestorInstructions, prevInstruction, _aux, _originalLink); }); - }, generatedUrl.urlPath, generatedUrl.urlParams.toArray()); + }, generatedUrl.urlPath, convertUrlParamsToArray(generatedUrl.urlParams)); } componentInstruction = _aux ? rules.generateAuxiliary(routeName, routeParams) : @@ -467,7 +467,7 @@ export class RouteRegistry { var defaultChild = null; if (isPresent(rules.defaultRule.handler.componentType)) { - var componentInstruction = rules.defaultRule.generate(new UrlParams()); + var componentInstruction = rules.defaultRule.generate({}); if (!rules.defaultRule.terminal) { defaultChild = this.generateDefault(rules.defaultRule.handler.componentType); } @@ -485,11 +485,11 @@ export class RouteRegistry { * Given: ['/a/b', {c: 2}] * Returns: ['', 'a', 'b', {c: 2}] */ -function splitAndFlattenLinkParams(linkParams) { +function splitAndFlattenLinkParams(linkParams : any[]) { var accumulation = []; - linkParams.forEach(function (item) { + linkParams.forEach(function (item : any) { if (isString(item)) { - var strItem = item; + var strItem : string = item; accumulation = accumulation.concat(strItem.split('/')); } else { accumulation.push(item); diff --git a/modules/angular2/src/router/rules/route_paths/param_route_path.ts b/modules/angular2/src/router/rules/route_paths/param_route_path.ts index 84472c49ee6c..fb30c7fa9229 100644 --- a/modules/angular2/src/router/rules/route_paths/param_route_path.ts +++ b/modules/angular2/src/router/rules/route_paths/param_route_path.ts @@ -3,7 +3,7 @@ import {BaseException} from 'angular2/src/facade/exceptions'; import {StringMapWrapper} from 'angular2/src/facade/collection'; import {TouchMap, normalizeString} from '../../utils'; -import {Url, RootUrl, UrlParams} from '../../url_parser'; +import {Url, RootUrl, convertUrlParamsToArray} from '../../url_parser'; import {RoutePath, GeneratedUrl, MatchedUrl} from './route_path'; @@ -156,18 +156,18 @@ export class ParamRoutePath implements RoutePath { if (isPresent(paramsSegment.params)) { allParams = StringMapWrapper.merge(paramsSegment.params, positionalParams); - urlParams = paramsSegment.params.toArray(); + urlParams = convertUrlParamsToArray(paramsSegment.params); } else { allParams = positionalParams; } auxiliary = currentUrlSegment.auxiliary; } - return new MatchedUrl(urlPath, urlParams, new UrlParams(allParams), auxiliary, nextUrlSegment); + return new MatchedUrl(urlPath, urlParams, allParams, auxiliary, nextUrlSegment); } - generateUrl(params: UrlParams): GeneratedUrl { + generateUrl(params: {[key: string]: any}): GeneratedUrl { var paramTokens = new TouchMap(params); var path = []; @@ -181,7 +181,7 @@ export class ParamRoutePath implements RoutePath { var urlPath = path.join('/'); var nonPositionalParams = paramTokens.getUnused(); - var urlParams = new UrlParams(nonPositionalParams); + var urlParams = nonPositionalParams; return new GeneratedUrl(urlPath, urlParams); } @@ -250,7 +250,7 @@ export class ParamRoutePath implements RoutePath { 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, hash; + var i, length = this._segments.length; var hashParts = []; for (i = 0; i < length; i++) { hashParts.push(this._segments[i].hash); @@ -259,15 +259,15 @@ export class ParamRoutePath implements RoutePath { } private _assertValidPath(path: string) { - const RESERVED_CHARS = RegExpWrapper.create('//|\\(|\\)|;|\\?|='); if (StringWrapper.contains(path, '#')) { throw new BaseException( `Path "${path}" should not include "#". Use "HashLocationStrategy" instead.`); } - var illegalCharacter = RegExpWrapper.firstMatch(RESERVED_CHARS, path); + 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('//|\\(|\\)|;|\\?|='); } diff --git a/modules/angular2/src/router/rules/route_paths/regex_route_path.ts b/modules/angular2/src/router/rules/route_paths/regex_route_path.ts index 8fc1fa1ed2e1..70bd68f6b4a4 100644 --- a/modules/angular2/src/router/rules/route_paths/regex_route_path.ts +++ b/modules/angular2/src/router/rules/route_paths/regex_route_path.ts @@ -1,9 +1,9 @@ -import {RegExpWrapper, isBlank} from 'angular2/src/facade/lang'; -import {Url, RootUrl, UrlParams} from '../../url_parser'; +import {RegExpWrapper, isBlank, StringWrapper} from 'angular2/src/facade/lang'; +import {Url, RootUrl} from '../../url_parser'; import {RoutePath, GeneratedUrl, MatchedUrl} from './route_path'; -export interface RegexSerializer { (params: UrlParams): GeneratedUrl } +export interface RegexSerializer { (params: {[key: string]: any}): GeneratedUrl } export class RegexRoutePath implements RoutePath { public hash: string; @@ -19,14 +19,16 @@ export class RegexRoutePath implements RoutePath { matchUrl(url: Url): MatchedUrl { var urlPath = url.toString(); - var match = RegExpWrapper.firstMatch(this._regex, urlPath); + var params: {[key: string]: string} = {} + var match; + + // this slightly weird method is used to prevent strange Dart type mismatch errors + StringWrapper.replaceAllMapped(urlPath, this._regex, (m) => { match = m; }); if (isBlank(match)) { return null; } - var params: UrlParams = new UrlParams(); - for (let i = 0; i < match.length; i += 1) { params[i.toString()] = match[i]; } @@ -34,7 +36,7 @@ export class RegexRoutePath implements RoutePath { return new MatchedUrl(urlPath, [], params, [], null); } - generateUrl(params: UrlParams): GeneratedUrl { return this._serializer(params); } + generateUrl(params: {[key: string]: any}): GeneratedUrl { return this._serializer(params); } toString() { return this._reString; diff --git a/modules/angular2/src/router/rules/route_paths/route_path.ts b/modules/angular2/src/router/rules/route_paths/route_path.ts index 4a6ea1e2470b..971eb6046dcb 100644 --- a/modules/angular2/src/router/rules/route_paths/route_path.ts +++ b/modules/angular2/src/router/rules/route_paths/route_path.ts @@ -1,13 +1,13 @@ -import {Url, UrlParams} from '../../url_parser'; +import {Url} from '../../url_parser'; export class MatchedUrl { - constructor(public urlPath: string, public urlParams: string[], public allParams: UrlParams, + 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: UrlParams) {} + constructor(public urlPath: string, public urlParams: {[key: string]: any}) {} } export interface RoutePath { @@ -15,6 +15,6 @@ export interface RoutePath { terminal: boolean; hash: string; matchUrl(url: Url): MatchedUrl; - generateUrl(params: UrlParams): GeneratedUrl; + generateUrl(params: {[key: string]: any}): GeneratedUrl; toString(): string; } diff --git a/modules/angular2/src/router/rules/rule_set.ts b/modules/angular2/src/router/rules/rule_set.ts index 1407a236a59a..219adbdcc90d 100644 --- a/modules/angular2/src/router/rules/rule_set.ts +++ b/modules/angular2/src/router/rules/rule_set.ts @@ -171,7 +171,7 @@ export class RuleSet { } private _getRoutePath(config : RouteDefinition) : RoutePath { - if (config.regex) { + if (isPresent(config.regex)) { if (isFunction(config.serializer)) { return new RegexRoutePath(config.regex, config.serializer); } else { @@ -179,7 +179,7 @@ export class RuleSet { `Route provides a regex property, '${config.regex}', but no serializer property`); } } - if (config.path) { + 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; diff --git a/modules/angular2/src/router/rules/rules.ts b/modules/angular2/src/router/rules/rules.ts index 75e5eb0b87e4..42cb94ecf022 100644 --- a/modules/angular2/src/router/rules/rules.ts +++ b/modules/angular2/src/router/rules/rules.ts @@ -4,7 +4,7 @@ import {PromiseWrapper} from 'angular2/src/facade/promise'; import {Map} from 'angular2/src/facade/collection'; import {RouteHandler} from './route_handlers/route_handler'; -import {Url, UrlParams} from '../url_parser'; +import {Url, convertUrlParamsToArray} from '../url_parser'; import {ComponentInstruction} from '../instruction'; import {RoutePath} from './route_paths/route_path'; import {GeneratedUrl} from './route_paths/route_path'; @@ -42,6 +42,9 @@ export class RedirectRule implements AbstractRule { 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 @@ -79,6 +82,9 @@ export class RouteRule implements AbstractRule { 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 { var res = this._routePath.matchUrl(beginningSegment); @@ -92,14 +98,14 @@ export class RouteRule implements AbstractRule { }); } - generate(params: UrlParams): ComponentInstruction { + generate(params: {[key: string]: any}): ComponentInstruction { var generated = this._routePath.generateUrl(params); var urlPath = generated.urlPath; var urlParams = generated.urlParams; - return this._getInstruction(urlPath, urlParams.toArray(), params); + return this._getInstruction(urlPath, convertUrlParamsToArray(urlParams), params); } - generateComponentPathValues(params: UrlParams): GeneratedUrl { + generateComponentPathValues(params: {[key: string]: any}): GeneratedUrl { return this._routePath.generateUrl(params); } diff --git a/modules/angular2/src/router/url_parser.ts b/modules/angular2/src/router/url_parser.ts index 2a6bdf4848df..b07d75dd19b6 100644 --- a/modules/angular2/src/router/url_parser.ts +++ b/modules/angular2/src/router/url_parser.ts @@ -2,28 +2,17 @@ import {StringMapWrapper} from 'angular2/src/facade/collection'; import {isPresent, isBlank, RegExpWrapper, CONST_EXPR} from 'angular2/src/facade/lang'; import {BaseException, WrappedException} from 'angular2/src/facade/exceptions'; -export class UrlParams { - [key: string]: any - - constructor(params : {[key: string]: any} = {}) { - if (isPresent(params)) { - StringMapWrapper.forEach(params, (value, key) => { - this[key] = value; - }); - } - } +export function convertUrlParamsToArray(urlParams : {[key: string]: any}) : string[] { + var paramsArray = []; + StringMapWrapper.forEach(urlParams, (value, key) => { + paramsArray.push((value === true) ? key : key + '=' + value); + }); + return paramsArray; +} - toArray() : string[] { - var params = []; - StringMapWrapper.forEach(this, (value, key) => { - if (value === true) { - params.push(key); - } else { - params.push(key + '=' + value); - } - }); - return params; - } +// 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); } /** @@ -32,7 +21,7 @@ export class UrlParams { export class Url { constructor(public path: string, public child: Url = null, public auxiliary: Url[] = CONST_EXPR([]), - public params: UrlParams = new UrlParams()) {} + public params: {[key: string]: any} = CONST_EXPR({})) {} toString(): string { return this.path + this._matrixParamsToString() + this._auxToString() + this._childString(); @@ -48,11 +37,11 @@ export class Url { } private _matrixParamsToString(): string { - if (isBlank(this.params)) { - return ''; + var paramString = serializeParams(this.params,';'); + if (paramString.length > 0) { + return ';' + paramString; } - - return ';' + this.params.toArray().join(';'); + return ''; } /** @internal */ @@ -61,7 +50,7 @@ export class Url { export class RootUrl extends Url { constructor(path: string, child: Url = null, auxiliary: Url[] = CONST_EXPR([]), - params: UrlParams = null) { + params: {[key: string]: any} = null) { super(path, child, auxiliary, params); } @@ -76,7 +65,7 @@ export class RootUrl extends Url { return ''; } - return '?' + this.params.toArray().join('&'); + return '?' + serializeParams(this.params); } } @@ -115,7 +104,7 @@ export class UrlParser { } // segment + (aux segments) + (query params) - parseRoot(): Url { + parseRoot(): RootUrl { if (this.peekStartsWith('/')) { this.capture('/'); } @@ -169,8 +158,8 @@ export class UrlParser { return new Url(path, child, aux, matrixParams); } - parseQueryParams(): UrlParams { - var params = new UrlParams(); + parseQueryParams(): {[key: string]: any} { + var params = {}; this.capture('?'); this.parseParam(params); while (this._remaining.length > 0 && this.peekStartsWith('&')) { @@ -180,8 +169,8 @@ export class UrlParser { return params; } - parseMatrixParams(): UrlParams { - var params = new UrlParams(); + parseMatrixParams(): {[key: string]: any} { + var params = {}; while (this._remaining.length > 0 && this.peekStartsWith(';')) { this.capture(';'); this.parseParam(params); @@ -189,7 +178,7 @@ export class UrlParser { return params; } - parseParam(params: UrlParams): void { + parseParam(params: {[key: string]: any}): void { var key = matchUrlSegment(this._remaining); if (isBlank(key)) { return; diff --git a/modules/angular2/test/router/rules/route_paths/param_route_path_spec.ts b/modules/angular2/test/router/rules/route_paths/param_route_path_spec.ts index 1456c82be1d4..94eaaf888d30 100644 --- a/modules/angular2/test/router/rules/route_paths/param_route_path_spec.ts +++ b/modules/angular2/test/router/rules/route_paths/param_route_path_spec.ts @@ -11,7 +11,7 @@ import { } from 'angular2/testing_internal'; import {ParamRoutePath} from 'angular2/src/router/rules/route_paths/param_route_path'; -import {parser, Url, UrlParams} from 'angular2/src/router/url_parser'; +import {parser, Url} from 'angular2/src/router/url_parser'; export function main() { describe('PathRecognizer', () => { @@ -53,14 +53,14 @@ export function main() { describe('matrix params', () => { it('should be parsed along with dynamic paths', () => { var rec = new ParamRoutePath('/hello/:id'); - var url = new Url('hello', new Url('matias', null, null, new UrlParams({'key': 'value'}))); + var url = new Url('hello', new Url('matias', null, null, {'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 ParamRoutePath('/person'); - var url = new Url('person', null, null, new UrlParams({'name': 'dave'})); + var url = new Url('person', null, null, {'name': 'dave'}); var match = rec.matchUrl(url); expect(match.allParams).toEqual({'name': 'dave'}); }); @@ -74,7 +74,7 @@ export function main() { it('should set matrix param values to true when no value is present', () => { var rec = new ParamRoutePath('/path'); - var url = new Url('path', null, null, new UrlParams({'one': true, 'two': true, 'three': '3'})); + var url = new Url('path', null, null, {'one': true, 'two': true, 'three': '3'}); var match = rec.matchUrl(url); expect(match.allParams).toEqual({'one': true, 'two': true, 'three': '3'}); }); @@ -82,9 +82,9 @@ export function main() { it('should be parsed on the final segment of the path', () => { var rec = new ParamRoutePath('/one/two/three'); - var three = new Url('three', null, null, new UrlParams({'c': '3'})); - var two = new Url('two', three, null, new UrlParams({'b': '2'})); - var one = new Url('one', two, null, new UrlParams({'a': '1'})); + 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.matchUrl(one); expect(match.allParams).toEqual({'c': '3'}); @@ -96,7 +96,7 @@ export function main() { var rec = new ParamRoutePath('/wild/*everything'); var url = parser.parse('/wild/super;variable=value/anotherPartAfterSlash'); var match = rec.matchUrl(url); - expect(match['urlPath']).toEqual('wild/super;variable=value/anotherPartAfterSlash'); + expect(match.urlPath).toEqual('wild/super;variable=value/anotherPartAfterSlash'); }); }); }); diff --git a/modules/angular2/test/router/rules/route_paths/regex_route_param_spec.ts b/modules/angular2/test/router/rules/route_paths/regex_route_param_spec.ts index 855f04aef3af..42d28ef12ac5 100644 --- a/modules/angular2/test/router/rules/route_paths/regex_route_param_spec.ts +++ b/modules/angular2/test/router/rules/route_paths/regex_route_param_spec.ts @@ -12,7 +12,9 @@ import { 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, UrlParams} from 'angular2/src/router/url_parser'; +import {parser, Url} from 'angular2/src/router/url_parser'; + +function emptySerializer(params) { return new GeneratedUrl('', {}); } export function main() { describe('RegexRoutePath', () => { @@ -38,13 +40,12 @@ export function main() { it('should generate a url by calling the provided serializer', () => { function serializer(params) { - return new GeneratedUrl(`/a/${params.a}/b/${params.b}`, new UrlParams()); + return new GeneratedUrl(`/a/${params.a}/b/${params.b}`, {}); } var rec = new RegexRoutePath('/a/(.+)/b/(.+)$', serializer); - var url = rec.generateUrl(new UrlParams({a: 'one', b: 'two'})); + var params = {a: 'one', b: 'two'}; + var url = rec.generateUrl(params); expect(url.urlPath).toEqual('/a/one/b/two'); }); - - function emptySerializer(params) { return new GeneratedUrl('', new UrlParams()); } }); } diff --git a/modules/angular2/test/router/rules/rule_set_spec.ts b/modules/angular2/test/router/rules/rule_set_spec.ts index 7191ce7b4ac4..40203e27d40e 100644 --- a/modules/angular2/test/router/rules/rule_set_spec.ts +++ b/modules/angular2/test/router/rules/rule_set_spec.ts @@ -15,7 +15,6 @@ import {Map, StringMapWrapper} from 'angular2/src/facade/collection'; 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 {UrlParams} from 'angular2/src/router/url_parser'; import {Route, Redirect} from 'angular2/src/router/route_config/route_config_decorator'; import {parser} from 'angular2/src/router/url_parser'; @@ -76,7 +75,7 @@ export function main() { it('should recognize a regex', inject([AsyncTestCompleter], (async) => { function emptySerializer(params): GeneratedUrl { - return new GeneratedUrl('', new UrlParams()); + return new GeneratedUrl('', {}); } recognizer.config(new Route({ @@ -146,7 +145,8 @@ export function main() { it('should generate using a serializer', () => { function simpleSerializer(params): GeneratedUrl { - return new GeneratedUrl(`/${params.a}/${params.b}`, new UrlParams({c: params.c})); + var extra = {c: params.c}; + return new GeneratedUrl(`/${params.a}/${params.b}`, extra); } recognizer.config(new Route({ @@ -155,7 +155,8 @@ export function main() { serializer: simpleSerializer, component: DummyCmpA })); - var result = recognizer.generate('Route1', { a: 'first', b:'second', c:'third'}); + 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']); }); diff --git a/modules/angular2/test/router/url_parser_spec.ts b/modules/angular2/test/router/url_parser_spec.ts index 12fd02c25ce6..e99efb6677e3 100644 --- a/modules/angular2/test/router/url_parser_spec.ts +++ b/modules/angular2/test/router/url_parser_spec.ts @@ -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(); }); From 002d4bfa43a8217af6ce783e785c9ac58d1d79f4 Mon Sep 17 00:00:00 2001 From: Peter Bacon Darwin Date: Fri, 26 Feb 2016 20:03:31 +0000 Subject: [PATCH 38/43] chore(angular_1_router): fix build to account for file refactoring --- modules/angular1_router/build.js | 21 ++++++++++++--------- 1 file changed, 12 insertions(+), 9 deletions(-) diff --git a/modules/angular1_router/build.js b/modules/angular1_router/build.js index 37f02c39afea..99bd7561efe5 100644 --- a/modules/angular1_router/build.js +++ b/modules/angular1_router/build.js @@ -4,17 +4,20 @@ var fs = require('fs'); var ts = require('typescript'); var files = [ - 'lifecycle_annotations_impl.ts', + 'utils.ts', 'url_parser.ts', - 'rules.ts', - 'route_config_impl.ts', - 'async_route_handler.ts', - 'sync_route_handler.ts', - 'rule_set.ts', + 'lifecycle/lifecycle_annotations_impl.ts', + 'lifecycle/route_lifecycle_reflector.ts', + 'route_config/route_config_impl.ts', + 'route_config/route_config_normalizer.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', - 'path_recognizer.ts', - 'route_config_nomalizer.ts', - 'route_lifecycle_reflector.ts', 'route_registry.ts', 'router.ts' ]; From b17d44dc8d0b4aa4965b15b49fd25494438cb44b Mon Sep 17 00:00:00 2001 From: Peter Bacon Darwin Date: Fri, 26 Feb 2016 20:21:07 +0000 Subject: [PATCH 39/43] style(router): fix formatting errors --- .../router/route_config/route_config_impl.ts | 36 ++++++++++++++++--- modules/angular2/src/router/route_registry.ts | 8 ++--- .../rules/route_paths/param_route_path.ts | 4 +-- .../rules/route_paths/regex_route_path.ts | 8 ++--- .../router/rules/route_paths/route_path.ts | 4 +-- modules/angular2/src/router/rules/rule_set.ts | 8 ++--- modules/angular2/src/router/rules/rules.ts | 24 +++++-------- modules/angular2/src/router/url_parser.ts | 11 +++--- .../route_paths/regex_route_param_spec.ts | 8 ++--- .../test/router/rules/rule_set_spec.ts | 26 ++++++-------- .../angular2/test/router/url_parser_spec.ts | 2 +- 11 files changed, 75 insertions(+), 64 deletions(-) diff --git a/modules/angular2/src/router/route_config/route_config_impl.ts b/modules/angular2/src/router/route_config/route_config_impl.ts index a81c0cf6ba48..f6f5a9fad662 100644 --- a/modules/angular2/src/router/route_config/route_config_impl.ts +++ b/modules/angular2/src/router/route_config/route_config_impl.ts @@ -61,7 +61,14 @@ export class Route extends AbstractRoute { aux: string = null; constructor({name, useAsDefault, path, regex, serializer, data, component}: RouteDefinition) { - super({name: name, useAsDefault: useAsDefault, path: path, regex: regex, serializer: serializer, data: data}); + super({ + name: name, + useAsDefault: useAsDefault, + path: path, + regex: regex, + serializer: serializer, + data: data + }); this.component = component; } } @@ -91,7 +98,14 @@ export class AuxRoute extends AbstractRoute { component: any; constructor({name, useAsDefault, path, regex, serializer, data, component}: RouteDefinition) { - super({name: name, useAsDefault: useAsDefault, path: path, regex: regex, serializer: serializer, data: data}); + super({ + name: name, + useAsDefault: useAsDefault, + path: path, + regex: regex, + serializer: serializer, + data: data + }); this.component = component; } } @@ -126,7 +140,14 @@ export class AsyncRoute extends AbstractRoute { aux: string = null; constructor({name, useAsDefault, path, regex, serializer, data, loader}: RouteDefinition) { - super({name: name, useAsDefault: useAsDefault, path: path, regex: regex, serializer: serializer, data: data}); + super({ + name: name, + useAsDefault: useAsDefault, + path: path, + regex: regex, + serializer: serializer, + data: data + }); this.loader = loader; } } @@ -157,7 +178,14 @@ export class Redirect extends AbstractRoute { redirectTo: any[]; constructor({name, useAsDefault, path, regex, serializer, data, redirectTo}: RouteDefinition) { - super({name: name, useAsDefault: useAsDefault, path: path, regex: regex, serializer: serializer, data: data}); + super({ + name: name, + useAsDefault: useAsDefault, + path: path, + regex: regex, + serializer: serializer, + data: data + }); this.redirectTo = redirectTo; } } diff --git a/modules/angular2/src/router/route_registry.ts b/modules/angular2/src/router/route_registry.ts index 21ca939ed912..fd765a4aa878 100644 --- a/modules/angular2/src/router/route_registry.ts +++ b/modules/angular2/src/router/route_registry.ts @@ -373,7 +373,7 @@ export class RouteRegistry { } let linkParamIndex = 0; - let routeParams : {[key: string]: any} = {}; + let routeParams: {[key: string]: any} = {}; // first, recognize the primary route if one is provided if (linkParamIndex < linkParams.length && isString(linkParams[linkParamIndex])) { @@ -485,11 +485,11 @@ export class RouteRegistry { * Given: ['/a/b', {c: 2}] * Returns: ['', 'a', 'b', {c: 2}] */ -function splitAndFlattenLinkParams(linkParams : any[]) { +function splitAndFlattenLinkParams(linkParams: any[]) { var accumulation = []; - linkParams.forEach(function (item : any) { + linkParams.forEach(function(item: any) { if (isString(item)) { - var strItem : string = item; + var strItem: string = item; accumulation = accumulation.concat(strItem.split('/')); } else { accumulation.push(item); diff --git a/modules/angular2/src/router/rules/route_paths/param_route_path.ts b/modules/angular2/src/router/rules/route_paths/param_route_path.ts index fb30c7fa9229..e8548749654c 100644 --- a/modules/angular2/src/router/rules/route_paths/param_route_path.ts +++ b/modules/angular2/src/router/rules/route_paths/param_route_path.ts @@ -187,9 +187,7 @@ export class ParamRoutePath implements RoutePath { } - toString(): string { - return this.routePath; - } + toString(): string { return this.routePath; } private _parsePathString(routePath: string) { // normalize route as not starting with a "/". Recognition will diff --git a/modules/angular2/src/router/rules/route_paths/regex_route_path.ts b/modules/angular2/src/router/rules/route_paths/regex_route_path.ts index 70bd68f6b4a4..614e24e0471e 100644 --- a/modules/angular2/src/router/rules/route_paths/regex_route_path.ts +++ b/modules/angular2/src/router/rules/route_paths/regex_route_path.ts @@ -3,7 +3,7 @@ import {Url, RootUrl} from '../../url_parser'; import {RoutePath, GeneratedUrl, MatchedUrl} from './route_path'; -export interface RegexSerializer { (params: {[key: string]: any}): GeneratedUrl } +export interface RegexSerializer { (params: {[key: string]: any}): GeneratedUrl; } export class RegexRoutePath implements RoutePath { public hash: string; @@ -19,7 +19,7 @@ export class RegexRoutePath implements RoutePath { matchUrl(url: Url): MatchedUrl { var urlPath = url.toString(); - var params: {[key: string]: string} = {} + var params: {[key: string]: string} = {}; var match; // this slightly weird method is used to prevent strange Dart type mismatch errors @@ -38,7 +38,5 @@ export class RegexRoutePath implements RoutePath { generateUrl(params: {[key: string]: any}): GeneratedUrl { return this._serializer(params); } - toString() { - return this._reString; - } + toString() { return this._reString; } } \ No newline at end of file diff --git a/modules/angular2/src/router/rules/route_paths/route_path.ts b/modules/angular2/src/router/rules/route_paths/route_path.ts index 971eb6046dcb..be1d5e1f6e98 100644 --- a/modules/angular2/src/router/rules/route_paths/route_path.ts +++ b/modules/angular2/src/router/rules/route_paths/route_path.ts @@ -1,8 +1,8 @@ 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) {} + constructor(public urlPath: string, public urlParams: string[], + public allParams: {[key: string]: any}, public auxiliary: Url[], public rest: Url) {} } diff --git a/modules/angular2/src/router/rules/rule_set.ts b/modules/angular2/src/router/rules/rule_set.ts index 219adbdcc90d..4b4dde5d3958 100644 --- a/modules/angular2/src/router/rules/rule_set.ts +++ b/modules/angular2/src/router/rules/rule_set.ts @@ -170,22 +170,22 @@ export class RuleSet { }); } - private _getRoutePath(config : RouteDefinition) : RoutePath { + 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`); + `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; + config.path.substring(1) : + config.path; return new ParamRoutePath(path); } throw new BaseException('Route must provide either a path or regex property'); } - } diff --git a/modules/angular2/src/router/rules/rules.ts b/modules/angular2/src/router/rules/rules.ts index 42cb94ecf022..289eef2d30bb 100644 --- a/modules/angular2/src/router/rules/rules.ts +++ b/modules/angular2/src/router/rules/rules.ts @@ -39,12 +39,8 @@ export class RedirectRule implements AbstractRule { 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'); - } + 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 @@ -73,18 +69,14 @@ export class RouteRule implements AbstractRule { // TODO: cache component instruction instances by params and by ParsedUrl instance - constructor(private _routePath : RoutePath, public handler: RouteHandler) { + constructor(private _routePath: RoutePath, public handler: RouteHandler) { this.specificity = this._routePath.specificity; this.hash = this._routePath.hash; this.terminal = this._routePath.terminal; } - get path() { - return this._routePath.toString(); - } - set path(val) { - throw new BaseException('you cannot set the path of a RouteRule directly'); - } + 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 { var res = this._routePath.matchUrl(beginningSegment); @@ -118,9 +110,9 @@ export class RouteRule implements AbstractRule { if (this._cache.has(hashKey)) { return this._cache.get(hashKey); } - var instruction = new ComponentInstruction(urlPath, urlParams, this.handler.data, - this.handler.componentType, this.terminal, - this.specificity, params); + var instruction = + new ComponentInstruction(urlPath, urlParams, this.handler.data, this.handler.componentType, + this.terminal, this.specificity, params); this._cache.set(hashKey, instruction); return instruction; diff --git a/modules/angular2/src/router/url_parser.ts b/modules/angular2/src/router/url_parser.ts index b07d75dd19b6..0fdeed985f2a 100644 --- a/modules/angular2/src/router/url_parser.ts +++ b/modules/angular2/src/router/url_parser.ts @@ -2,16 +2,15 @@ import {StringMapWrapper} from 'angular2/src/facade/collection'; import {isPresent, isBlank, RegExpWrapper, CONST_EXPR} from 'angular2/src/facade/lang'; import {BaseException, WrappedException} from 'angular2/src/facade/exceptions'; -export function convertUrlParamsToArray(urlParams : {[key: string]: any}) : string[] { +export function convertUrlParamsToArray(urlParams: {[key: string]: any}): string[] { var paramsArray = []; - StringMapWrapper.forEach(urlParams, (value, key) => { - paramsArray.push((value === true) ? key : key + '=' + value); - }); + 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 { +export function serializeParams(urlParams: {[key: string]: any}, joiner = '&'): string { return convertUrlParamsToArray(urlParams).join(joiner); } @@ -37,7 +36,7 @@ export class Url { } private _matrixParamsToString(): string { - var paramString = serializeParams(this.params,';'); + var paramString = serializeParams(this.params, ';'); if (paramString.length > 0) { return ';' + paramString; } diff --git a/modules/angular2/test/router/rules/route_paths/regex_route_param_spec.ts b/modules/angular2/test/router/rules/route_paths/regex_route_param_spec.ts index 42d28ef12ac5..17f7a5ad00e5 100644 --- a/modules/angular2/test/router/rules/route_paths/regex_route_param_spec.ts +++ b/modules/angular2/test/router/rules/route_paths/regex_route_param_spec.ts @@ -14,7 +14,9 @@ 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('', {}); } +function emptySerializer(params) { + return new GeneratedUrl('', {}); +} export function main() { describe('RegexRoutePath', () => { @@ -39,9 +41,7 @@ export function main() { }); it('should generate a url by calling the provided serializer', () => { - function serializer(params) { - return new GeneratedUrl(`/a/${params.a}/b/${params.b}`, {}); - } + 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); diff --git a/modules/angular2/test/router/rules/rule_set_spec.ts b/modules/angular2/test/router/rules/rule_set_spec.ts index 40203e27d40e..8315f86aa82a 100644 --- a/modules/angular2/test/router/rules/rule_set_spec.ts +++ b/modules/angular2/test/router/rules/rule_set_spec.ts @@ -74,23 +74,19 @@ export function main() { })); it('should recognize a regex', inject([AsyncTestCompleter], (async) => { - function emptySerializer(params): GeneratedUrl { - return new GeneratedUrl('', {}); - } + 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); + 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'}); + 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', () => { @@ -155,7 +151,7 @@ export function main() { serializer: simpleSerializer, component: DummyCmpA })); - var params = { a: 'first', b:'second', c:'third'}; + 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']); diff --git a/modules/angular2/test/router/url_parser_spec.ts b/modules/angular2/test/router/url_parser_spec.ts index e99efb6677e3..e9dfba0b2659 100644 --- a/modules/angular2/test/router/url_parser_spec.ts +++ b/modules/angular2/test/router/url_parser_spec.ts @@ -15,7 +15,7 @@ import {UrlParser, Url} from 'angular2/src/router/url_parser'; export function main() { describe('ParsedUrl', () => { - var urlParser : UrlParser; + var urlParser: UrlParser; beforeEach(() => { urlParser = new UrlParser(); }); From a3ee427c916aac115f6d032bee3e3d5ccc876c83 Mon Sep 17 00:00:00 2001 From: Peter Bacon Darwin Date: Fri, 26 Feb 2016 20:25:17 +0000 Subject: [PATCH 40/43] test(router): relax regex error message --- .../test/router/rules/route_paths/regex_route_param_spec.ts | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/modules/angular2/test/router/rules/route_paths/regex_route_param_spec.ts b/modules/angular2/test/router/rules/route_paths/regex_route_param_spec.ts index 17f7a5ad00e5..fddced2d3367 100644 --- a/modules/angular2/test/router/rules/route_paths/regex_route_param_spec.ts +++ b/modules/angular2/test/router/rules/route_paths/regex_route_param_spec.ts @@ -21,10 +21,8 @@ function emptySerializer(params) { export function main() { describe('RegexRoutePath', () => { - it('should throw when given an invalid regex', () => { - expect(() => new RegexRoutePath('[abc', emptySerializer)) - .toThrowError('Invalid regular expression: /[abc/: Unterminated character class'); - }); + 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); From 070c36fc0c0517f1266f417165b427adceb7c419 Mon Sep 17 00:00:00 2001 From: Peter Bacon Darwin Date: Fri, 26 Feb 2016 21:56:00 +0000 Subject: [PATCH 41/43] fix(router): handle trying to serialize non-existent urlParams --- modules/angular2/src/router/url_parser.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/modules/angular2/src/router/url_parser.ts b/modules/angular2/src/router/url_parser.ts index 0fdeed985f2a..a208222ffc94 100644 --- a/modules/angular2/src/router/url_parser.ts +++ b/modules/angular2/src/router/url_parser.ts @@ -4,6 +4,9 @@ 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; From 26cf7157836205e713541a05da7f8cc6bbbfd425 Mon Sep 17 00:00:00 2001 From: Peter Bacon Darwin Date: Fri, 26 Feb 2016 22:22:45 +0000 Subject: [PATCH 42/43] refactor(router): fix un-dartable code --- .../src/router/rules/route_paths/regex_route_path.ts | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/modules/angular2/src/router/rules/route_paths/regex_route_path.ts b/modules/angular2/src/router/rules/route_paths/regex_route_path.ts index 614e24e0471e..39559363b571 100644 --- a/modules/angular2/src/router/rules/route_paths/regex_route_path.ts +++ b/modules/angular2/src/router/rules/route_paths/regex_route_path.ts @@ -1,4 +1,4 @@ -import {RegExpWrapper, isBlank, StringWrapper} from 'angular2/src/facade/lang'; +import {RegExpWrapper, RegExpMatcherWrapper, isBlank} from 'angular2/src/facade/lang'; import {Url, RootUrl} from '../../url_parser'; import {RoutePath, GeneratedUrl, MatchedUrl} from './route_path'; @@ -20,10 +20,8 @@ export class RegexRoutePath implements RoutePath { matchUrl(url: Url): MatchedUrl { var urlPath = url.toString(); var params: {[key: string]: string} = {}; - var match; - - // this slightly weird method is used to prevent strange Dart type mismatch errors - StringWrapper.replaceAllMapped(urlPath, this._regex, (m) => { match = m; }); + var matcher = RegExpWrapper.matcher(this._regex, urlPath); + var match = RegExpMatcherWrapper.next(matcher); if (isBlank(match)) { return null; From 411cfb7eaec17dc141c5ab5ef9aaffdd9c42d396 Mon Sep 17 00:00:00 2001 From: Peter Bacon Darwin Date: Fri, 26 Feb 2016 22:54:36 +0000 Subject: [PATCH 43/43] chore(node_tree): fix path to excluded router test --- tools/broccoli/trees/node_tree.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/broccoli/trees/node_tree.ts b/tools/broccoli/trees/node_tree.ts index cb60b1c548f8..d3d39097f3c4 100644 --- a/tools/broccoli/trees/node_tree.ts +++ b/tools/broccoli/trees/node_tree.ts @@ -72,7 +72,7 @@ module.exports = function makeNodeTree(projects, destinationPath) { 'angular2/test/common/forms/**', // 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', // we check the public api by importing angular2/angular2