refactor(router): convert to typescript

Fixes #2001
This commit is contained in:
Jeff Cross
2015-05-29 14:58:41 -07:00
parent 4c8e11a577
commit ba07f39347
31 changed files with 900 additions and 977 deletions

View File

@ -110,10 +110,10 @@ export class DomAdapter {
cssToRules(css: string): List<any> { throw _abstract(); }
supportsDOMEvents(): boolean { throw _abstract(); }
supportsNativeShadowDOM(): boolean { throw _abstract(); }
getGlobalEventTarget(target: string) { throw _abstract(); }
getHistory() { throw _abstract(); }
getLocation() { throw _abstract(); }
getBaseHref() { throw _abstract(); }
getGlobalEventTarget(target: string): any { throw _abstract(); }
getHistory(): any { throw _abstract(); }
getLocation(): any { throw _abstract(); }
getBaseHref(): string { throw _abstract(); }
getUserAgent(): string { throw _abstract(); }
setData(element, name: string, value: string) { throw _abstract(); }
getData(element, name: string): string { throw _abstract(); }

View File

@ -15,7 +15,11 @@ export 'dart:html'
Node,
MouseEvent,
KeyboardEvent,
Event;
Event,
EventTarget,
History,
Location,
EventListener;
final _gc = context['gc'];

View File

@ -10,3 +10,7 @@ export var gc = window['gc'] ? () => window['gc']() : () => null;
export const Event = Event;
export const MouseEvent = MouseEvent;
export const KeyboardEvent = KeyboardEvent;
export const EventTarget = EventTarget;
export const History = History;
export const Location = Location;
export const EventListener = EventListener;

View File

@ -9,10 +9,10 @@ import {Location} from 'angular2/src/router/location';
@proxy
@IMPLEMENTS(Location)
export class SpyLocation extends SpyObject {
urlChanges:List<string>;
_path:string;
_subject:EventEmitter;
_baseHref:string;
urlChanges: List<string>;
_path: string;
_subject: EventEmitter;
_baseHref: string;
constructor() {
super();
@ -22,29 +22,17 @@ export class SpyLocation extends SpyObject {
this._baseHref = '';
}
setInitialPath(url:string) {
this._path = url;
}
setInitialPath(url: string) { this._path = url; }
setBaseHref(url:string) {
this._baseHref = url;
}
setBaseHref(url: string) { this._baseHref = url; }
path():string {
return this._path;
}
path(): string { return this._path; }
simulateUrlPop(pathname:string) {
ObservableWrapper.callNext(this._subject, {
'url': pathname
});
}
simulateUrlPop(pathname: string) { ObservableWrapper.callNext(this._subject, {'url': pathname}); }
normalizeAbsolutely(url) {
return this._baseHref + url;
}
normalizeAbsolutely(url) { return this._baseHref + url; }
go(url:string) {
go(url: string) {
url = this.normalizeAbsolutely(url);
if (this._path == url) {
return;
@ -65,5 +53,5 @@ export class SpyLocation extends SpyObject {
ObservableWrapper.subscribe(this._subject, onNext, onThrow, onReturn);
}
noSuchMethod(m){return super.noSuchMethod(m);}
noSuchMethod(m) { return super.noSuchMethod(m); }
}

View File

@ -1,37 +0,0 @@
import {DOM} from 'angular2/src/dom/dom_adapter';
export class BrowserLocation {
_location;
_history;
_baseHref:string;
constructor() {
this._location = DOM.getLocation();
this._history = DOM.getHistory();
this._baseHref = DOM.getBaseHref();
}
onPopState(fn: Function): void {
DOM.getGlobalEventTarget('window').addEventListener('popstate', fn, false);
}
getBaseHref(): string {
return this._baseHref;
}
path(): string {
return this._location.pathname;
}
pushState(state:any, title:string, url:string) {
this._history.pushState(state, title, url);
}
forward(): void {
this._history.forward();
}
back(): void {
this._history.back();
}
}

View File

@ -0,0 +1,30 @@
import {DOM} from 'angular2/src/dom/dom_adapter';
import {Injectable} from 'angular2/di';
import {EventListener, History, Location} from 'angular2/src/facade/browser';
@Injectable()
export class BrowserLocation {
private _location: Location;
private _history: History;
private _baseHref: string;
constructor() {
this._location = DOM.getLocation();
this._history = DOM.getHistory();
this._baseHref = DOM.getBaseHref();
}
onPopState(fn: EventListener): void {
DOM.getGlobalEventTarget('window').addEventListener('popstate', fn, false);
}
getBaseHref(): string { return this._baseHref; }
path(): string { return this._location.pathname; }
pushState(state: any, title: string, url: string) { this._history.pushState(state, title, url); }
forward(): void { this._history.forward(); }
back(): void { this._history.back(); }
}

View File

@ -1,37 +1,44 @@
import {Map, MapWrapper, StringMap, StringMapWrapper, List, ListWrapper} from 'angular2/src/facade/collection';
import {
Map,
MapWrapper,
StringMap,
StringMapWrapper,
List,
ListWrapper
} from 'angular2/src/facade/collection';
import {Promise, PromiseWrapper} from 'angular2/src/facade/async';
import {isPresent, normalizeBlank} from 'angular2/src/facade/lang';
export class RouteParams {
params:StringMap<string, string>;
constructor(public params: StringMap<string, string>) {}
constructor(params:StringMap) {
this.params = params;
}
get(param:string): string {
return normalizeBlank(StringMapWrapper.get(this.params, param));
}
get(param: string): string { return normalizeBlank(StringMapWrapper.get(this.params, param)); }
}
/**
* An `Instruction` represents the component hierarchy of the application based on a given route
*/
export class Instruction {
component:any;
_children:Map<string, Instruction>;
component: any;
private _children: StringMap<string, Instruction>;
// the part of the URL captured by this instruction
capturedUrl:string;
capturedUrl: string;
// the part of the URL captured by this instruction and all children
accumulatedUrl:string;
accumulatedUrl: string;
params:StringMap<string, string>;
reuse:boolean;
specificity:number;
params: StringMap<string, string>;
reuse: boolean;
specificity: number;
constructor({params, component, children, matchedUrl, parentSpecificity}:{params:StringMap, component:any, children:Map, matchedUrl:string, parentSpecificity:number} = {}) {
constructor({params, component, children, matchedUrl, parentSpecificity}: {
params?: StringMap<string, any>,
component?: any,
children?: StringMap<string, Instruction>,
matchedUrl?: string,
parentSpecificity?: number
} = {}) {
this.reuse = false;
this.capturedUrl = matchedUrl;
this.accumulatedUrl = matchedUrl;
@ -53,39 +60,38 @@ export class Instruction {
this.params = params;
}
hasChild(outletName:string):boolean {
hasChild(outletName: string): boolean {
return StringMapWrapper.contains(this._children, outletName);
}
/**
* Returns the child instruction with the given outlet name
*/
getChild(outletName:string):Instruction {
getChild(outletName: string): Instruction {
return StringMapWrapper.get(this._children, outletName);
}
/**
* (child:Instruction, outletName:string) => {}
*/
forEachChild(fn:Function): void {
StringMapWrapper.forEach(this._children, fn);
}
forEachChild(fn: Function): void { StringMapWrapper.forEach(this._children, fn); }
/**
* Does a synchronous, breadth-first traversal of the graph of instructions.
* Takes a function with signature:
* (child:Instruction, outletName:string) => {}
*/
traverseSync(fn:Function): void {
traverseSync(fn: Function): void {
this.forEachChild(fn);
this.forEachChild((childInstruction, _) => childInstruction.traverseSync(fn));
}
/**
* Takes a currently active instruction and sets a reuse flag on each of this instruction's children
* Takes a currently active instruction and sets a reuse flag on each of this instruction's
* children
*/
reuseComponentsFrom(oldInstruction:Instruction): void {
reuseComponentsFrom(oldInstruction: Instruction): void {
this.traverseSync((childInstruction, outletName) => {
var oldInstructionChild = oldInstruction.getChild(outletName);
if (shouldReuseComponent(childInstruction, oldInstructionChild)) {
@ -95,16 +101,16 @@ export class Instruction {
}
}
function shouldReuseComponent(instr1:Instruction, instr2:Instruction): boolean {
function shouldReuseComponent(instr1: Instruction, instr2: Instruction): boolean {
return instr1.component == instr2.component &&
StringMapWrapper.equals(instr1.params, instr2.params);
StringMapWrapper.equals(instr1.params, instr2.params);
}
function mapObjAsync(obj:StringMap, fn): Promise {
function mapObjAsync(obj: StringMap<string, any>, fn): Promise<List<any>> {
return PromiseWrapper.all(mapObj(obj, fn));
}
function mapObj(obj:StringMap, fn: Function):List {
function mapObj(obj: StringMap<any, any>, fn: Function): List<any> {
var result = ListWrapper.create();
StringMapWrapper.forEach(obj, (value, key) => ListWrapper.push(result, fn(value, key)));
return result;

View File

@ -1,31 +1,24 @@
import {BrowserLocation} from './browser_location';
import {StringWrapper} from 'angular2/src/facade/lang';
import {EventEmitter, ObservableWrapper} from 'angular2/src/facade/async';
import {Injectable} from 'angular2/di';
@Injectable()
export class Location {
_subject:EventEmitter;
_browserLocation:BrowserLocation;
_baseHref:string;
constructor(browserLocation:BrowserLocation) {
private _subject: EventEmitter;
private _baseHref: string;
constructor(public _browserLocation: BrowserLocation) {
this._subject = new EventEmitter();
this._browserLocation = browserLocation;
this._baseHref = stripIndexHtml(this._browserLocation.getBaseHref());
this._browserLocation.onPopState((_) => this._onPopState(_));
}
_onPopState(_): void {
ObservableWrapper.callNext(this._subject, {
'url': this.path()
});
}
_onPopState(_): void { ObservableWrapper.callNext(this._subject, {'url': this.path()}); }
path(): string {
return this.normalize(this._browserLocation.path());
}
path(): string { return this.normalize(this._browserLocation.path()); }
normalize(url: string): string {
return this._stripBaseHref(stripIndexHtml(url));
}
normalize(url: string): string { return this._stripBaseHref(stripIndexHtml(url)); }
normalizeAbsolutely(url: string): string {
if (url[0] != '/') {
@ -48,18 +41,14 @@ export class Location {
return url;
}
go(url:string): void {
go(url: string): void {
var finalUrl = this.normalizeAbsolutely(url);
this._browserLocation.pushState(null, '', finalUrl);
}
forward(): void {
this._browserLocation.forward();
}
forward(): void { this._browserLocation.forward(); }
back(): void {
this._browserLocation.back();
}
back(): void { this._browserLocation.back(); }
subscribe(onNext, onThrow = null, onReturn = null): void {
ObservableWrapper.subscribe(this._subject, onNext, onThrow, onReturn);

View File

@ -1,35 +1,54 @@
import {RegExp, RegExpWrapper, RegExpMatcherWrapper, StringWrapper, isPresent, isBlank, BaseException, normalizeBlank} from 'angular2/src/facade/lang';
import {Map, MapWrapper, StringMap, StringMapWrapper, List, ListWrapper} from 'angular2/src/facade/collection';
import {
RegExp,
RegExpWrapper,
RegExpMatcherWrapper,
StringWrapper,
isPresent,
isBlank,
BaseException,
normalizeBlank
} from 'angular2/src/facade/lang';
import {
Map,
MapWrapper,
StringMap,
StringMapWrapper,
List,
ListWrapper
} from 'angular2/src/facade/collection';
import {IMPLEMENTS} from 'angular2/src/facade/lang';
import {escapeRegex} from './url';
class StaticSegment {
string:string;
regex:string;
name:string;
// TODO(jeffbcross): implement as interface when ts2dart adds support:
// https://github.com/angular/ts2dart/issues/173
export class Segment {
name: string;
regex: string;
}
constructor(string:string) {
this.string = string;
class StaticSegment extends Segment {
regex: string;
name: string;
constructor(public string: string) {
super();
this.name = '';
this.regex = escapeRegex(string);
}
generate(params): string {
return this.string;
}
generate(params): string { return this.string; }
}
@IMPLEMENTS(Segment)
class DynamicSegment {
name:string;
regex:string;
constructor(name:string) {
this.name = name;
this.regex = "([^/]+)";
}
regex: string;
constructor(public name: string) { this.regex = "([^/]+)"; }
generate(params:StringMap<string, string>): string {
generate(params: StringMap<string, string>): string {
if (!StringMapWrapper.contains(params, this.name)) {
throw new BaseException(`Route generator for '${this.name}' was not included in parameters passed.`)
throw new BaseException(
`Route generator for '${this.name}' was not included in parameters passed.`)
}
return normalizeBlank(StringMapWrapper.get(params, this.name));
}
@ -37,14 +56,10 @@ class DynamicSegment {
class StarSegment {
name:string;
regex:string;
constructor(name:string) {
this.name = name;
this.regex = "(.+)";
}
regex: string;
constructor(public name: string) { this.regex = "(.+)"; }
generate(params:StringMap<string, string>): string {
generate(params: StringMap<string, string>): string {
return normalizeBlank(StringMapWrapper.get(params, this.name));
}
}
@ -53,7 +68,7 @@ class StarSegment {
var paramMatcher = RegExpWrapper.create("^:([^\/]+)$");
var wildcardMatcher = RegExpWrapper.create("^\\*([^\/]+)$");
function parsePathString(route:string) {
function parsePathString(route: string) {
// normalize route as not starting with a "/". Recognition will
// also normalize.
if (route[0] === "/") {
@ -64,19 +79,22 @@ function parsePathString(route:string) {
var results = ListWrapper.create();
var specificity = 0;
// 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
// 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 integer that we can
// sort later. Each static segment is worth hundreds of points of specificity (10000, 9900, ..., 200), and each
// The code below uses place values to combine the different types of segments into a single
// integer that we can
// sort later. Each static segment is worth hundreds of points of specificity (10000, 9900, ...,
// 200), and each
// dynamic segment is worth single points of specificity (100, 99, ... 2).
if (segments.length > 98) {
throw new BaseException(`'${route}' has more than the maximum supported number of segments.`);
}
for (var i=0; i<segments.length; i++) {
var segment = segments[i],
match;
for (var i = 0; i < segments.length; i++) {
var segment = segments[i], match;
if (isPresent(match = RegExpWrapper.firstMatch(paramMatcher, segment))) {
ListWrapper.push(results, new DynamicSegment(match[1]));
@ -92,22 +110,18 @@ function parsePathString(route:string) {
return {segments: results, specificity};
}
function splitBySlash (url:string):List<string> {
function splitBySlash(url: string): List<string> {
return url.split('/');
}
// represents something like '/foo/:bar'
export class PathRecognizer {
segments:List;
regex:RegExp;
handler:any;
specificity:number;
path:string;
segments: List<Segment>;
regex: RegExp;
specificity: number;
constructor(path:string, handler:any) {
this.path = path;
this.handler = handler;
constructor(public path: string, public handler: any) {
this.segments = [];
// TODO: use destructuring assignment
@ -117,19 +131,17 @@ export class PathRecognizer {
var segments = parsed['segments'];
var regexString = '^';
ListWrapper.forEach(segments, (segment) => {
regexString += '/' + segment.regex;
});
ListWrapper.forEach(segments, (segment) => { regexString += '/' + segment.regex; });
this.regex = RegExpWrapper.create(regexString);
this.segments = segments;
this.specificity = specificity;
}
parseParams(url:string):StringMap<string, string> {
parseParams(url: string): StringMap<string, string> {
var params = StringMapWrapper.create();
var urlPart = url;
for(var i=0; i<this.segments.length; i++) {
for (var i = 0; i < this.segments.length; i++) {
var segment = this.segments[i];
var match = RegExpWrapper.firstMatch(RegExpWrapper.create('/' + segment.regex), urlPart);
urlPart = StringWrapper.substring(urlPart, match[0].length);
@ -141,8 +153,8 @@ export class PathRecognizer {
return params;
}
generate(params:StringMap<string, string>):string {
return ListWrapper.join(ListWrapper.map(this.segments, (segment) =>
'/' + segment.generate(params)), '');
generate(params: StringMap<string, string>): string {
return ListWrapper.join(
ListWrapper.map(this.segments, (segment) => '/' + segment.generate(params)), '');
}
}

View File

@ -7,19 +7,14 @@ import {Instruction} from './instruction';
* "Steps" are conceptually similar to "middleware"
*/
export class Pipeline {
steps:List<Function>;
steps: List<Function>;
constructor() {
this.steps = [
instruction => instruction.router.activateOutlets(instruction)
];
}
constructor() { this.steps = [instruction => instruction.router.activateOutlets(instruction)]; }
process(instruction:Instruction):Promise {
var steps = this.steps,
currentStep = 0;
process(instruction: Instruction): Promise<any> {
var steps = this.steps, currentStep = 0;
function processOne(result:any = true):Promise {
function processOne(result: any = true): Promise<any> {
if (currentStep >= steps.length) {
return PromiseWrapper.resolve(result);
}

View File

@ -1,3 +0,0 @@
library angular2.router.route_config_annotations;
export './route_config_impl.dart';

View File

@ -1 +0,0 @@
export {RouteConfig as RouteConfigAnnotation} from './route_config_impl';

View File

@ -1,3 +1,3 @@
library angular2.router.route_config_decorator;
/** This file is intentionally empty, as Dart does not have decorators */
export './route_config_impl.dart';

View File

@ -2,4 +2,3 @@ import {RouteConfig as RouteConfigAnnotation} from './route_config_impl';
import {makeDecorator} from 'angular2/src/util/decorators';
export var RouteConfig = makeDecorator(RouteConfigAnnotation);

View File

@ -9,11 +9,7 @@ import {List, Map} from 'angular2/src/facade/collection';
* - `component`, `components`, `redirectTo` (requires exactly one of these)
* - `as` (optional)
*/
@CONST()
export class RouteConfig {
configs:List<Map>;
@CONST()
constructor(configs:List<Map>) {
this.configs = configs;
}
constructor(public configs: List<Map<any, any>>) {}
}

View File

@ -1,16 +1,30 @@
import {RegExp, RegExpWrapper, StringWrapper, isPresent, BaseException} from 'angular2/src/facade/lang';
import {Map, MapWrapper, List, ListWrapper, StringMap, StringMapWrapper} from 'angular2/src/facade/collection';
import {
RegExp,
RegExpWrapper,
StringWrapper,
isPresent,
BaseException
} from 'angular2/src/facade/lang';
import {
Map,
MapWrapper,
List,
ListWrapper,
StringMap,
StringMapWrapper
} from 'angular2/src/facade/collection';
import {PathRecognizer} from './path_recognizer';
/**
* `RouteRecognizer` is responsible for recognizing routes for a single component.
* It is consumed by `RouteRegistry`, which knows how to recognize an entire hierarchy of components.
* It is consumed by `RouteRegistry`, which knows how to recognize an entire hierarchy of
* components.
*/
export class RouteRecognizer {
names:Map<string, PathRecognizer>;
redirects:Map<string, string>;
matchers:Map<RegExp, PathRecognizer>;
names: Map<string, PathRecognizer>;
redirects: Map<string, string>;
matchers: Map<RegExp, PathRecognizer>;
constructor() {
this.names = MapWrapper.create();
@ -18,15 +32,14 @@ export class RouteRecognizer {
this.redirects = MapWrapper.create();
}
addRedirect(path:string, target:string): void {
MapWrapper.set(this.redirects, path, target);
}
addRedirect(path: string, target: string): void { MapWrapper.set(this.redirects, path, target); }
addConfig(path:string, handler:any, alias:string = null): void {
addConfig(path: string, handler: any, alias: string = null): void {
var recognizer = new PathRecognizer(path, handler);
MapWrapper.forEach(this.matchers, (matcher, _) => {
if (recognizer.regex.toString() == matcher.regex.toString()) {
throw new BaseException(`Configuration '${path}' conflicts with existing route '${matcher.path}'`);
throw new BaseException(
`Configuration '${path}' conflicts with existing route '${matcher.path}'`);
}
});
MapWrapper.set(this.matchers, recognizer.regex, recognizer);
@ -40,11 +53,11 @@ export class RouteRecognizer {
* Given a URL, returns a list of `RouteMatch`es, which are partial recognitions for some route.
*
*/
recognize(url:string):List<RouteMatch> {
recognize(url: string): List<RouteMatch> {
var solutions = ListWrapper.create();
MapWrapper.forEach(this.redirects, (target, path) => {
//TODO: "/" redirect case
// TODO: "/" redirect case
if (StringWrapper.startsWith(url, path)) {
url = target + StringWrapper.substring(url, path.length);
}
@ -53,7 +66,7 @@ export class RouteRecognizer {
MapWrapper.forEach(this.matchers, (pathRecognizer, regex) => {
var match;
if (isPresent(match = RegExpWrapper.firstMatch(regex, url))) {
//TODO(btford): determine a good generic way to deal with terminal matches
// TODO(btford): determine a good generic way to deal with terminal matches
var matchedUrl = '/';
var unmatchedUrl = '';
if (url != '/') {
@ -61,37 +74,39 @@ export class RouteRecognizer {
unmatchedUrl = StringWrapper.substring(url, match[0].length);
}
ListWrapper.push(solutions, new RouteMatch({
specificity: pathRecognizer.specificity,
handler: pathRecognizer.handler,
params: pathRecognizer.parseParams(url),
matchedUrl: matchedUrl,
unmatchedUrl: unmatchedUrl
}));
specificity: pathRecognizer.specificity,
handler: pathRecognizer.handler,
params: pathRecognizer.parseParams(url),
matchedUrl: matchedUrl,
unmatchedUrl: unmatchedUrl
}));
}
});
return solutions;
}
hasRoute(name:string): boolean {
return MapWrapper.contains(this.names, name);
}
hasRoute(name: string): boolean { return MapWrapper.contains(this.names, name); }
generate(name:string, params:any): string {
generate(name: string, params: any): string {
var pathRecognizer = MapWrapper.get(this.names, name);
return isPresent(pathRecognizer) ? pathRecognizer.generate(params) : null;
}
}
export class RouteMatch {
specificity:number;
handler:StringMap<string, any>;
params:StringMap<string, string>;
matchedUrl:string;
unmatchedUrl:string;
constructor({specificity, handler, params, matchedUrl, unmatchedUrl}:
{specificity:number, handler:StringMap, params:StringMap, matchedUrl:string, unmatchedUrl:string} = {}) {
specificity: number;
handler: StringMap<string, any>;
params: StringMap<string, string>;
matchedUrl: string;
unmatchedUrl: string;
constructor({specificity, handler, params, matchedUrl, unmatchedUrl}: {
specificity?: number,
handler?: StringMap<string, any>,
params?: StringMap<string, string>,
matchedUrl?: string,
unmatchedUrl?: string
} = {}) {
this.specificity = specificity;
this.handler = handler;
this.params = params;

View File

@ -1,25 +1,31 @@
import {RouteRecognizer, RouteMatch} from './route_recognizer';
import {Instruction, noopInstruction} from './instruction';
import {List, ListWrapper, Map, MapWrapper, StringMap, StringMapWrapper} from 'angular2/src/facade/collection';
import {Instruction} from './instruction';
import {
List,
ListWrapper,
Map,
MapWrapper,
StringMap,
StringMapWrapper
} from 'angular2/src/facade/collection';
import {isPresent, isBlank, isType, StringWrapper, BaseException} from 'angular2/src/facade/lang';
import {RouteConfig} from './route_config_impl';
import {reflector} from 'angular2/src/reflection/reflection';
/**
* The RouteRegistry holds route configurations for each component in an Angular app.
* It is responsible for creating Instructions from URLs, and generating URLs based on route and parameters.
* It is responsible for creating Instructions from URLs, and generating URLs based on route and
* parameters.
*/
export class RouteRegistry {
_rules:Map<any, RouteRecognizer>;
_rules: Map<any, RouteRecognizer>;
constructor() {
this._rules = MapWrapper.create();
}
constructor() { this._rules = MapWrapper.create(); }
/**
* Given a component and a configuration object, add the route to this registry
*/
config(parentComponent, config:StringMap<string, any>): void {
config(parentComponent, config: StringMap<string, any>): void {
if (!StringMapWrapper.contains(config, 'path')) {
throw new BaseException('Route config does not contain "path"');
}
@ -27,10 +33,11 @@ export class RouteRegistry {
if (!StringMapWrapper.contains(config, 'component') &&
!StringMapWrapper.contains(config, 'components') &&
!StringMapWrapper.contains(config, 'redirectTo')) {
throw new BaseException('Route config does not contain "component," "components," or "redirectTo"');
throw new BaseException(
'Route config does not contain "component," "components," or "redirectTo"');
}
var recognizer:RouteRecognizer = MapWrapper.get(this._rules, parentComponent);
var recognizer: RouteRecognizer = MapWrapper.get(this._rules, parentComponent);
if (isBlank(recognizer)) {
recognizer = new RouteRecognizer();
@ -65,7 +72,7 @@ export class RouteRegistry {
}
var annotations = reflector.annotations(component);
if (isPresent(annotations)) {
for (var i=0; i<annotations.length; i++) {
for (var i = 0; i < annotations.length; i++) {
var annotation = annotations[i];
if (annotation instanceof RouteConfig) {
@ -80,7 +87,7 @@ export class RouteRegistry {
* Given a URL and a parent component, return the most specific instruction for navigating
* the application into the state specified by the
*/
recognize(url:string, parentComponent): Instruction {
recognize(url: string, parentComponent): Instruction {
var componentRecognizer = MapWrapper.get(this._rules, parentComponent);
if (isBlank(componentRecognizer)) {
return null;
@ -93,16 +100,15 @@ export class RouteRegistry {
var fullSolutions = ListWrapper.create();
for (var i = 0; i < possibleMatches.length; i++) {
var candidate : RouteMatch = possibleMatches[i];
var candidate: RouteMatch = possibleMatches[i];
// if the candidate captures all of the URL, add it to our list of solutions
if (candidate.unmatchedUrl.length == 0) {
ListWrapper.push(fullSolutions, routeMatchToInstruction(candidate, parentComponent));
} else {
// otherwise, recursively match the remaining part of the URL against the component's children
var children = StringMapWrapper.create(),
allChildrenMatch = true,
// otherwise, recursively match the remaining part of the URL against the component's
// children
var children = StringMapWrapper.create(), allChildrenMatch = true,
components = StringMapWrapper.get(candidate.handler, 'components');
var componentNames = StringMapWrapper.keys(components);
@ -122,11 +128,11 @@ export class RouteRegistry {
if (allChildrenMatch) {
ListWrapper.push(fullSolutions, new Instruction({
component: parentComponent,
children: children,
matchedUrl: candidate.matchedUrl,
parentSpecificity: candidate.specificity
}));
component: parentComponent,
children: children,
matchedUrl: candidate.matchedUrl,
parentSpecificity: candidate.specificity
}));
}
}
}
@ -146,22 +152,19 @@ export class RouteRegistry {
return null;
}
generate(name:string, params:StringMap<string, string>, hostComponent): string {
//TODO: implement for hierarchical routes
generate(name: string, params: StringMap<string, string>, hostComponent): string {
// TODO: implement for hierarchical routes
var componentRecognizer = MapWrapper.get(this._rules, hostComponent);
return isPresent(componentRecognizer) ? componentRecognizer.generate(name, params) : null;
}
}
function routeMatchToInstruction(routeMatch:RouteMatch, parentComponent): Instruction {
function routeMatchToInstruction(routeMatch: RouteMatch, parentComponent): Instruction {
var children = StringMapWrapper.create();
var components = StringMapWrapper.get(routeMatch.handler, 'components');
StringMapWrapper.forEach(components, (component, outletName) => {
children[outletName] = new Instruction({
component: component,
params: routeMatch.params,
parentSpecificity: 0
});
children[outletName] =
new Instruction({component: component, params: routeMatch.params, parentSpecificity: 0});
});
return new Instruction({
component: parentComponent,
@ -181,15 +184,11 @@ function routeMatchToInstruction(routeMatch:RouteMatch, parentComponent): Instru
* If the config object does not contain a `component` key, the original
* config object is returned.
*/
function normalizeConfig(config:StringMap<string, any>): StringMap<string, any> {
function normalizeConfig(config: StringMap<string, any>): StringMap<string, any> {
if (!StringMapWrapper.contains(config, 'component')) {
return config;
}
var newConfig = {
'components': {
'default': config['component']
}
};
var newConfig = {'components': {'default': config['component']}};
StringMapWrapper.forEach(config, (value, key) => {
if (key != 'component' && key != 'components') {

View File

@ -21,51 +21,44 @@ import {Location} from './location';
* The router holds reference to a number of "outlets." An outlet is a placeholder that the
* router dynamically fills in depending on the current URL.
*
* When the router navigates from a URL, it must first recognizes it and serialize it into an `Instruction`.
* When the router navigates from a URL, it must first recognizes it and serialize it into an
* `Instruction`.
* The router uses the `RouteRegistry` to get an `Instruction`.
*
* @exportedAs angular2/router
*/
export class Router {
hostComponent:any;
parent:Router;
navigating:boolean;
navigating: boolean;
lastNavigationAttempt: string;
previousUrl:string;
previousUrl: string;
_currentInstruction:Instruction;
_pipeline:Pipeline;
_registry:RouteRegistry;
_outlets:Map<any, RouterOutlet>;
_subject:EventEmitter;
constructor(registry:RouteRegistry, pipeline:Pipeline, parent:Router, hostComponent:any) {
this.hostComponent = hostComponent;
private _currentInstruction: Instruction;
private _outlets: Map<any, RouterOutlet>;
private _subject: EventEmitter;
// todo(jeffbcross): rename _registry to registry since it is accessed from subclasses
// todo(jeffbcross): rename _pipeline to pipeline since it is accessed from subclasses
constructor(public _registry: RouteRegistry, public _pipeline: Pipeline, public parent: Router,
public hostComponent: any) {
this.navigating = false;
this.parent = parent;
this.previousUrl = null;
this._outlets = MapWrapper.create();
this._registry = registry;
this._pipeline = pipeline;
this._subject = new EventEmitter();
this._currentInstruction = null;
}
/**
* Constructs a child router. You probably don't need to use this unless you're writing a reusable component.
* Constructs a child router. You probably don't need to use this unless you're writing a reusable
* component.
*/
childRouter(hostComponent:any): Router {
return new ChildRouter(this, hostComponent);
}
childRouter(hostComponent: any): Router { return new ChildRouter(this, hostComponent); }
/**
* Register an object to notify of route changes. You probably don't need to use this unless you're writing a reusable component.
* Register an object to notify of route changes. You probably don't need to use this unless
* you're writing a reusable component.
*/
registerOutlet(outlet:RouterOutlet, name: string = 'default'): Promise {
registerOutlet(outlet: RouterOutlet, name: string = 'default'): Promise<boolean> {
MapWrapper.set(this._outlets, name, outlet);
if (isPresent(this._currentInstruction)) {
var childInstruction = this._currentInstruction.getChild(name);
@ -94,11 +87,10 @@ export class Router {
* ```
*
*/
config(config:any): Promise {
config(config: any): Promise<any> {
if (config instanceof List) {
config.forEach((configObject) => {
this._registry.config(this.hostComponent, configObject);
});
config.forEach(
(configObject) => { this._registry.config(this.hostComponent, configObject); });
} else {
this._registry.config(this.hostComponent, config);
}
@ -112,7 +104,7 @@ export class Router {
* If the given URL begins with a `/`, router will navigate absolutely.
* If the given URL does not begin with `/`, the router will navigate relative to this component.
*/
navigate(url:string):Promise {
navigate(url: string): Promise<any> {
if (this.navigating) {
return PromiseWrapper.resolve(true);
}
@ -132,37 +124,31 @@ export class Router {
this._startNavigating();
var result = this.commit(matchedInstruction)
.then((_) => {
ObservableWrapper.callNext(this._subject, matchedInstruction.accumulatedUrl);
this._finishNavigating();
});
.then((_) => {
ObservableWrapper.callNext(this._subject, matchedInstruction.accumulatedUrl);
this._finishNavigating();
});
PromiseWrapper.catchError(result, (_) => this._finishNavigating());
return result;
}
_startNavigating(): void {
this.navigating = true;
}
_startNavigating(): void { this.navigating = true; }
_finishNavigating(): void {
this.navigating = false;
}
_finishNavigating(): void { this.navigating = false; }
/**
* Subscribe to URL updates from the router
*/
subscribe(onNext): void {
ObservableWrapper.subscribe(this._subject, onNext);
}
subscribe(onNext): void { ObservableWrapper.subscribe(this._subject, onNext); }
/**
*
*/
commit(instruction:Instruction):Promise {
commit(instruction: Instruction): Promise<List<any>> {
this._currentInstruction = instruction;
// collect all outlets that do not have a corresponding child instruction
@ -184,37 +170,32 @@ export class Router {
* Recursively remove all components contained by this router's outlets.
* Calls deactivate hooks on all descendant components
*/
deactivate():Promise {
return this._eachOutletAsync((outlet) => outlet.deactivate);
}
deactivate(): Promise<any> { return this._eachOutletAsync((outlet) => outlet.deactivate); }
/**
* Recursively activate.
* Calls the "activate" hook on descendant components.
*/
activate(instruction:Instruction):Promise {
activate(instruction: Instruction): Promise<any> {
return this._eachOutletAsync((outlet, name) => outlet.activate(instruction.getChild(name)));
}
_eachOutletAsync(fn):Promise {
return mapObjAsync(this._outlets, fn);
}
_eachOutletAsync(fn): Promise<any> { return mapObjAsync(this._outlets, fn); }
/**
* Given a URL, returns an instruction representing the component graph
*/
recognize(url:string): Instruction {
return this._registry.recognize(url, this.hostComponent);
}
recognize(url: string): Instruction { return this._registry.recognize(url, this.hostComponent); }
/**
* Navigates to either the last URL successfully navigated to, or the last URL requested if the router has yet to successfully navigate.
* Navigates to either the last URL successfully navigated to, or the last URL requested if the
* router has yet to successfully navigate.
*/
renavigate():Promise {
renavigate(): Promise<any> {
var destination = isBlank(this.previousUrl) ? this.lastNavigationAttempt : this.previousUrl;
if (this.navigating || isBlank(destination)) {
return PromiseWrapper.resolve(false);
@ -224,17 +205,19 @@ export class Router {
/**
* Generate a URL from a component name and optional map of parameters. The URL is relative to the app's base href.
* Generate a URL from a component name and optional map of parameters. The URL is relative to the
* app's base href.
*/
generate(name:string, params:StringMap<string, string>): string {
generate(name: string, params: StringMap<string, string>): string {
return this._registry.generate(name, params, this.hostComponent);
}
}
export class RootRouter extends Router {
_location:Location;
_location: Location;
constructor(registry:RouteRegistry, pipeline:Pipeline, location:Location, hostComponent:Type) {
constructor(registry: RouteRegistry, pipeline: Pipeline, location: Location,
hostComponent: Type) {
super(registry, pipeline, null, hostComponent);
this._location = location;
this._location.subscribe((change) => this.navigate(change['url']));
@ -242,25 +225,24 @@ export class RootRouter extends Router {
this.navigate(location.path());
}
commit(instruction):Promise {
return super.commit(instruction).then((_) => {
this._location.go(instruction.accumulatedUrl);
});
commit(instruction): Promise<any> {
return super.commit(instruction)
.then((_) => { this._location.go(instruction.accumulatedUrl); });
}
}
class ChildRouter extends Router {
constructor(parent:Router, hostComponent) {
constructor(parent: Router, hostComponent) {
super(parent._registry, parent._pipeline, parent, hostComponent);
this.parent = parent;
}
}
function mapObjAsync(obj:Map, fn): Promise {
function mapObjAsync(obj: Map<any, any>, fn: Function): Promise<any> {
return PromiseWrapper.all(mapObj(obj, fn));
}
function mapObj(obj:Map, fn):List {
function mapObj(obj: Map<any, any>, fn: Function): List<any> {
var result = ListWrapper.create();
MapWrapper.forEach(obj, (value, key) => ListWrapper.push(result, fn(value, key)));
return result;

View File

@ -1,4 +1,5 @@
import {Directive, onAllChangesDone} from 'angular2/src/core/annotations_impl/annotations';
import {onAllChangesDone} from 'angular2/src/core/annotations/annotations';
import {Directive} from 'angular2/src/core/annotations/decorators';
import {ElementRef} from 'angular2/core';
import {StringMap, StringMapWrapper} from 'angular2/src/facade/collection';
@ -31,27 +32,21 @@ import {Location} from './location';
*/
@Directive({
selector: '[router-link]',
properties: [
'route: routerLink',
'params: routerParams'
],
properties: ['route: routerLink', 'params: routerParams'],
lifecycle: [onAllChangesDone]
})
export class RouterLink {
_domEl;
_route:string;
_params:StringMap<string, string>;
_router:Router;
_location:Location;
private _domEl;
private _route: string;
private _params: StringMap<string, string>;
// the url displayed on the anchor element.
_visibleHref: string;
// the url passed to the router navigation.
_navigationHref: string;
constructor(elementRef:ElementRef, router:Router, location:Location) {
constructor(elementRef: ElementRef, private _router: Router, private _location: Location) {
this._domEl = elementRef.domElement;
this._router = router;
this._location = location;
this._params = StringMapWrapper.create();
DOM.on(this._domEl, 'click', (evt) => {
DOM.preventDefault(evt);
@ -59,13 +54,9 @@ export class RouterLink {
});
}
set route(changes: string) {
this._route = changes;
}
set route(changes: string) { this._route = changes; }
set params(changes: StringMap) {
this._params = changes;
}
set params(changes: StringMap<string, string>) { this._params = changes; }
onAllChangesDone(): void {
if (isPresent(this._route) && isPresent(this._params)) {

View File

@ -1,8 +1,7 @@
import {Promise, PromiseWrapper} from 'angular2/src/facade/async';
import {isBlank, isPresent} from 'angular2/src/facade/lang';
import {Directive} from 'angular2/src/core/annotations_impl/annotations';
import {Attribute} from 'angular2/src/core/annotations_impl/di';
import {Directive, Attribute} from 'angular2/src/core/annotations/decorators';
import {DynamicComponentLoader, ComponentRef, ElementRef} from 'angular2/core';
import {Injector, bind} from 'angular2/di';
@ -31,22 +30,19 @@ import {Instruction, RouteParams} from './instruction'
selector: 'router-outlet'
})
export class RouterOutlet {
_injector:Injector;
_parentRouter:routerMod.Router;
_childRouter:routerMod.Router;
_loader:DynamicComponentLoader;
_componentRef:ComponentRef;
_elementRef:ElementRef;
_currentInstruction:Instruction;
private _childRouter: routerMod.Router;
private _componentRef: ComponentRef;
private _elementRef: ElementRef;
private _currentInstruction: Instruction;
constructor(elementRef:ElementRef, loader:DynamicComponentLoader, router:routerMod.Router, injector:Injector, @Attribute('name') nameAttr:String) {
constructor(elementRef: ElementRef, private _loader: DynamicComponentLoader,
private _parentRouter: routerMod.Router, private _injector: Injector,
@Attribute('name') nameAttr: string) {
if (isBlank(nameAttr)) {
nameAttr = 'default';
}
this._loader = loader;
this._parentRouter = router;
this._elementRef = elementRef;
this._injector = injector;
this._childRouter = null;
this._componentRef = null;
@ -57,17 +53,20 @@ export class RouterOutlet {
/**
* Given an instruction, update the contents of this viewport.
*/
activate(instruction:Instruction): Promise {
// if we're able to reuse the component, we just have to pass along the instruction to the component's router
activate(instruction: Instruction): Promise<any> {
// if we're able to reuse the component, we just have to pass along the instruction to the
// component's router
// so it can propagate changes to its children
if ((instruction == this._currentInstruction) || instruction.reuse && isPresent(this._childRouter)) {
if ((instruction == this._currentInstruction) ||
instruction.reuse && isPresent(this._childRouter)) {
return this._childRouter.commit(instruction);
}
this._currentInstruction = instruction;
this._childRouter = this._parentRouter.childRouter(instruction.component);
var outletInjector = this._injector.resolveAndCreateChild([
bind(RouteParams).toValue(new RouteParams(instruction.params)),
bind(RouteParams)
.toValue(new RouteParams(instruction.params)),
bind(routerMod.Router).toValue(this._childRouter)
]);
@ -75,18 +74,21 @@ export class RouterOutlet {
this._componentRef.dispose();
}
return this._loader.loadNextToExistingLocation(instruction.component, this._elementRef, outletInjector).then((componentRef) => {
this._componentRef = componentRef;
return this._childRouter.commit(instruction);
});
return this._loader.loadNextToExistingLocation(instruction.component, this._elementRef,
outletInjector)
.then((componentRef) => {
this._componentRef = componentRef;
return this._childRouter.commit(instruction);
});
}
deactivate():Promise {
return (isPresent(this._childRouter) ? this._childRouter.deactivate() : PromiseWrapper.resolve(true))
.then((_) =>this._componentRef.dispose());
deactivate(): Promise<any> {
return (isPresent(this._childRouter) ? this._childRouter.deactivate() :
PromiseWrapper.resolve(true))
.then((_) => this._componentRef.dispose());
}
canDeactivate(instruction:Instruction): Promise<boolean> {
canDeactivate(instruction: Instruction): Promise<boolean> {
// TODO: how to get ahold of the component instance here?
return PromiseWrapper.resolve(true);
}

View File

@ -1,13 +1,9 @@
import {RegExpWrapper, StringWrapper} from 'angular2/src/facade/lang';
var specialCharacters = [
'/', '.', '*', '+', '?', '|', '(', ')', '[', ']', '{', '}', '\\'
];
var specialCharacters = ['/', '.', '*', '+', '?', '|', '(', ')', '[', ']', '{', '}', '\\'];
var escapeRe = RegExpWrapper.create('(\\' + specialCharacters.join('|\\') + ')', 'g');
export function escapeRegex(string:string): string {
return StringWrapper.replaceAllMapped(string, escapeRe, (match) => {
return "\\" + match;
});
export function escapeRegex(string: string): string {
return StringWrapper.replaceAllMapped(string, escapeRe, (match) => { return "\\" + match; });
}