diff --git a/modules/angular2/src/alt_router/router_url_parser.ts b/modules/angular2/src/alt_router/router_url_parser.ts new file mode 100644 index 0000000000..b57662b7c1 --- /dev/null +++ b/modules/angular2/src/alt_router/router_url_parser.ts @@ -0,0 +1,27 @@ +import {UrlSegment, Tree} from './segments'; +import {BaseException} from 'angular2/src/facade/exceptions'; + +export abstract class RouterUrlParser { abstract parse(url: string): Tree; } + +export class DefaultRouterUrlParser extends RouterUrlParser { + parse(url: string): Tree { + if (url.length === 0) { + throw new BaseException(`Invalid url '${url}'`); + } + return new Tree(this._parseNodes(url)); + } + + private _parseNodes(url: string): UrlSegment[] { + let index = url.indexOf("/", 1); + let children: UrlSegment[]; + let currentUrl; + if (index > -1) { + children = this._parseNodes(url.substring(index + 1)); + currentUrl = url.substring(0, index); + } else { + children = []; + currentUrl = url; + } + return [new UrlSegment(currentUrl, {}, "")].concat(children); + } +} \ No newline at end of file diff --git a/modules/angular2/test/alt_router/router_url_parser_spec.ts b/modules/angular2/test/alt_router/router_url_parser_spec.ts new file mode 100644 index 0000000000..b7d0b0398e --- /dev/null +++ b/modules/angular2/test/alt_router/router_url_parser_spec.ts @@ -0,0 +1,45 @@ +import { + ComponentFixture, + AsyncTestCompleter, + TestComponentBuilder, + beforeEach, + ddescribe, + xdescribe, + describe, + el, + expect, + iit, + inject, + beforeEachProviders, + it, + xit +} from 'angular2/testing_internal'; + +import {DefaultRouterUrlParser} from 'angular2/src/alt_router/router_url_parser'; +import {UrlSegment} from 'angular2/src/alt_router/segments'; + +export function main() { + describe('url parsing', () => { + let parser = new DefaultRouterUrlParser(); + + it('should throw on an empty urls', () => { expect(() => parser.parse("")).toThrow(); }); + + it('should parse the root url', () => { + let tree = parser.parse("/"); + expect(tree.root).toEqual(new UrlSegment("/", {}, "")); + }); + + it('should parse non-empty urls', () => { + let tree = parser.parse("one/two/three"); + expect(tree.root).toEqual(new UrlSegment("one", {}, "")); + expect(tree.firstChild(tree.root)).toEqual(new UrlSegment("two", {}, "")); + expect(tree.firstChild(tree.firstChild(tree.root))).toEqual(new UrlSegment("three", {}, "")); + }); + + it('should parse non-empty absolute urls', () => { + let tree = parser.parse("/one/two"); + expect(tree.root).toEqual(new UrlSegment("/one", {}, "")); + expect(tree.firstChild(tree.root)).toEqual(new UrlSegment("two", {}, "")); + }); + }); +} \ No newline at end of file