feat(router): add regex matchers
@petebacondarwin deserves credit for most of this commit. This allows you to specify a regex and serializer function instead of the path DSL in your route declaration. ``` @RouteConfig([ { regex: '[a-z]+.[0-9]+', serializer: (params) => `{params.a}.params.b}`, component: MyComponent } ]) class Component {} ``` Closes #7325 Closes #7126
This commit is contained in:
parent
2548ce86db
commit
75343eb340
|
@ -4,17 +4,20 @@ var fs = require('fs');
|
|||
var ts = require('typescript');
|
||||
|
||||
var files = [
|
||||
'lifecycle_annotations_impl.ts',
|
||||
'utils.ts',
|
||||
'url_parser.ts',
|
||||
'route_recognizer.ts',
|
||||
'route_config_impl.ts',
|
||||
'async_route_handler.ts',
|
||||
'sync_route_handler.ts',
|
||||
'component_recognizer.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'
|
||||
];
|
||||
|
|
|
@ -200,7 +200,6 @@ function ngOutletFillContentDirective($compile) {
|
|||
|
||||
|
||||
|
||||
|
||||
function routerTriggerDirective($q) {
|
||||
return {
|
||||
require: '^ngOutlet',
|
||||
|
|
|
@ -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);
|
||||
}));
|
||||
|
||||
|
|
|
@ -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";
|
||||
|
|
|
@ -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';
|
||||
|
|
|
@ -5,26 +5,26 @@
|
|||
*/
|
||||
|
||||
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/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 * from './src/router/route_config_decorator';
|
||||
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/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';
|
||||
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';
|
||||
|
||||
/**
|
||||
|
|
|
@ -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.
|
||||
|
|
|
@ -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.
|
||||
|
|
|
@ -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';
|
||||
|
||||
|
||||
/**
|
||||
|
|
|
@ -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_
|
||||
|
|
|
@ -1,163 +0,0 @@
|
|||
import {isBlank, isPresent} from 'angular2/src/facade/lang';
|
||||
import {BaseException, WrappedException} from 'angular2/src/facade/exceptions';
|
||||
import {Map, MapWrapper, ListWrapper, StringMapWrapper} from 'angular2/src/facade/collection';
|
||||
import {PromiseWrapper} from 'angular2/src/facade/async';
|
||||
|
||||
import {
|
||||
AbstractRecognizer,
|
||||
RouteRecognizer,
|
||||
RedirectRecognizer,
|
||||
RouteMatch,
|
||||
PathMatch
|
||||
} from './route_recognizer';
|
||||
import {Route, AsyncRoute, AuxRoute, Redirect, RouteDefinition} from './route_config_impl';
|
||||
import {AsyncRouteHandler} from './async_route_handler';
|
||||
import {SyncRouteHandler} from './sync_route_handler';
|
||||
import {Url} from './url_parser';
|
||||
import {ComponentInstruction} from './instruction';
|
||||
|
||||
|
||||
/**
|
||||
* `ComponentRecognizer` is responsible for recognizing routes for a single component.
|
||||
* It is consumed by `RouteRegistry`, which knows how to recognize an entire hierarchy of
|
||||
* components.
|
||||
*/
|
||||
export class ComponentRecognizer {
|
||||
names = new Map<string, RouteRecognizer>();
|
||||
|
||||
// map from name to recognizer
|
||||
auxNames = new Map<string, RouteRecognizer>();
|
||||
|
||||
// map from starting path to recognizer
|
||||
auxRoutes = new Map<string, RouteRecognizer>();
|
||||
|
||||
// TODO: optimize this into a trie
|
||||
matchers: AbstractRecognizer[] = [];
|
||||
|
||||
defaultRoute: RouteRecognizer = null;
|
||||
|
||||
/**
|
||||
* returns whether or not the config is terminal
|
||||
*/
|
||||
config(config: RouteDefinition): boolean {
|
||||
var handler;
|
||||
|
||||
if (isPresent(config.name) && config.name[0].toUpperCase() != config.name[0]) {
|
||||
var suggestedName = config.name[0].toUpperCase() + config.name.substring(1);
|
||||
throw new BaseException(
|
||||
`Route "${config.path}" with name "${config.name}" does not begin with an uppercase letter. Route names should be CamelCase like "${suggestedName}".`);
|
||||
}
|
||||
|
||||
if (config instanceof AuxRoute) {
|
||||
handler = new SyncRouteHandler(config.component, config.data);
|
||||
let path = config.path.startsWith('/') ? config.path.substring(1) : config.path;
|
||||
var recognizer = new RouteRecognizer(config.path, handler);
|
||||
this.auxRoutes.set(path, recognizer);
|
||||
if (isPresent(config.name)) {
|
||||
this.auxNames.set(config.name, recognizer);
|
||||
}
|
||||
return recognizer.terminal;
|
||||
}
|
||||
|
||||
var useAsDefault = false;
|
||||
|
||||
if (config instanceof Redirect) {
|
||||
let redirector = new RedirectRecognizer(config.path, config.redirectTo);
|
||||
this._assertNoHashCollision(redirector.hash, config.path);
|
||||
this.matchers.push(redirector);
|
||||
return true;
|
||||
}
|
||||
|
||||
if (config instanceof Route) {
|
||||
handler = new SyncRouteHandler(config.component, config.data);
|
||||
useAsDefault = isPresent(config.useAsDefault) && config.useAsDefault;
|
||||
} else if (config instanceof AsyncRoute) {
|
||||
handler = new AsyncRouteHandler(config.loader, config.data);
|
||||
useAsDefault = isPresent(config.useAsDefault) && config.useAsDefault;
|
||||
}
|
||||
var recognizer = new RouteRecognizer(config.path, handler);
|
||||
|
||||
this._assertNoHashCollision(recognizer.hash, config.path);
|
||||
|
||||
if (useAsDefault) {
|
||||
if (isPresent(this.defaultRoute)) {
|
||||
throw new BaseException(`Only one route can be default`);
|
||||
}
|
||||
this.defaultRoute = recognizer;
|
||||
}
|
||||
|
||||
this.matchers.push(recognizer);
|
||||
if (isPresent(config.name)) {
|
||||
this.names.set(config.name, recognizer);
|
||||
}
|
||||
return recognizer.terminal;
|
||||
}
|
||||
|
||||
|
||||
private _assertNoHashCollision(hash: string, path) {
|
||||
this.matchers.forEach((matcher) => {
|
||||
if (hash == matcher.hash) {
|
||||
throw new BaseException(
|
||||
`Configuration '${path}' conflicts with existing route '${matcher.path}'`);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Given a URL, returns a list of `RouteMatch`es, which are partial recognitions for some route.
|
||||
*/
|
||||
recognize(urlParse: Url): Promise<RouteMatch>[] {
|
||||
var solutions = [];
|
||||
|
||||
this.matchers.forEach((routeRecognizer: AbstractRecognizer) => {
|
||||
var pathMatch = routeRecognizer.recognize(urlParse);
|
||||
|
||||
if (isPresent(pathMatch)) {
|
||||
solutions.push(pathMatch);
|
||||
}
|
||||
});
|
||||
|
||||
// handle cases where we are routing just to an aux route
|
||||
if (solutions.length == 0 && isPresent(urlParse) && urlParse.auxiliary.length > 0) {
|
||||
return [PromiseWrapper.resolve(new PathMatch(null, null, urlParse.auxiliary))];
|
||||
}
|
||||
|
||||
return solutions;
|
||||
}
|
||||
|
||||
recognizeAuxiliary(urlParse: Url): Promise<RouteMatch>[] {
|
||||
var routeRecognizer: RouteRecognizer = this.auxRoutes.get(urlParse.path);
|
||||
if (isPresent(routeRecognizer)) {
|
||||
return [routeRecognizer.recognize(urlParse)];
|
||||
}
|
||||
|
||||
return [PromiseWrapper.resolve(null)];
|
||||
}
|
||||
|
||||
hasRoute(name: string): boolean { return this.names.has(name); }
|
||||
|
||||
componentLoaded(name: string): boolean {
|
||||
return this.hasRoute(name) && isPresent(this.names.get(name).handler.componentType);
|
||||
}
|
||||
|
||||
loadComponent(name: string): Promise<any> {
|
||||
return this.names.get(name).handler.resolveComponentType();
|
||||
}
|
||||
|
||||
generate(name: string, params: any): ComponentInstruction {
|
||||
var pathRecognizer: RouteRecognizer = this.names.get(name);
|
||||
if (isBlank(pathRecognizer)) {
|
||||
return null;
|
||||
}
|
||||
return pathRecognizer.generate(params);
|
||||
}
|
||||
|
||||
generateAuxiliary(name: string, params: any): ComponentInstruction {
|
||||
var pathRecognizer: RouteRecognizer = this.auxNames.get(name);
|
||||
if (isBlank(pathRecognizer)) {
|
||||
return null;
|
||||
}
|
||||
return pathRecognizer.generate(params);
|
||||
}
|
||||
}
|
|
@ -1,9 +1,9 @@
|
|||
import {Directive} from 'angular2/core';
|
||||
import {isString} from 'angular2/src/facade/lang';
|
||||
|
||||
import {Router} from './router';
|
||||
import {Location} from './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.
|
|
@ -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_annotations';
|
||||
import {hasLifecycleHook} from './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);
|
||||
|
|
@ -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<ComponentInstruction> {
|
||||
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) {
|
||||
|
|
|
@ -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,
|
|
@ -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';
|
||||
|
|
@ -1,281 +0,0 @@
|
|||
import {
|
||||
RegExp,
|
||||
RegExpWrapper,
|
||||
RegExpMatcherWrapper,
|
||||
StringWrapper,
|
||||
isPresent,
|
||||
isBlank
|
||||
} from 'angular2/src/facade/lang';
|
||||
import {BaseException, WrappedException} from 'angular2/src/facade/exceptions';
|
||||
import {Map, MapWrapper, StringMapWrapper} from 'angular2/src/facade/collection';
|
||||
|
||||
import {Url, RootUrl, serializeParams} from './url_parser';
|
||||
|
||||
class TouchMap {
|
||||
map: {[key: string]: string} = {};
|
||||
keys: {[key: string]: boolean} = {};
|
||||
|
||||
constructor(map: {[key: string]: any}) {
|
||||
if (isPresent(map)) {
|
||||
StringMapWrapper.forEach(map, (value, key) => {
|
||||
this.map[key] = isPresent(value) ? value.toString() : null;
|
||||
this.keys[key] = true;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
get(key: string): string {
|
||||
StringMapWrapper.delete(this.keys, key);
|
||||
return this.map[key];
|
||||
}
|
||||
|
||||
getUnused(): {[key: string]: any} {
|
||||
var unused: {[key: string]: any} = {};
|
||||
var keys = StringMapWrapper.keys(this.keys);
|
||||
keys.forEach(key => unused[key] = StringMapWrapper.get(this.map, key));
|
||||
return unused;
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeString(obj: any): string {
|
||||
if (isBlank(obj)) {
|
||||
return null;
|
||||
} else {
|
||||
return obj.toString();
|
||||
}
|
||||
}
|
||||
|
||||
interface Segment {
|
||||
name: string;
|
||||
generate(params: TouchMap): string;
|
||||
match(path: string): boolean;
|
||||
}
|
||||
|
||||
class ContinuationSegment implements Segment {
|
||||
name: string = '';
|
||||
generate(params: TouchMap): string { return ''; }
|
||||
match(path: string): boolean { return true; }
|
||||
}
|
||||
|
||||
class StaticSegment implements Segment {
|
||||
name: string = '';
|
||||
constructor(public path: string) {}
|
||||
match(path: string): boolean { return path == this.path; }
|
||||
generate(params: TouchMap): string { return this.path; }
|
||||
}
|
||||
|
||||
class DynamicSegment implements Segment {
|
||||
constructor(public name: string) {}
|
||||
match(path: string): boolean { return path.length > 0; }
|
||||
generate(params: TouchMap): string {
|
||||
if (!StringMapWrapper.contains(params.map, this.name)) {
|
||||
throw new BaseException(
|
||||
`Route generator for '${this.name}' was not included in parameters passed.`);
|
||||
}
|
||||
return normalizeString(params.get(this.name));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
class StarSegment implements Segment {
|
||||
constructor(public name: string) {}
|
||||
match(path: string): boolean { return true; }
|
||||
generate(params: TouchMap): string { return normalizeString(params.get(this.name)); }
|
||||
}
|
||||
|
||||
|
||||
var paramMatcher = /^:([^\/]+)$/g;
|
||||
var wildcardMatcher = /^\*([^\/]+)$/g;
|
||||
|
||||
function parsePathString(route: string): {[key: string]: any} {
|
||||
// normalize route as not starting with a "/". Recognition will
|
||||
// also normalize.
|
||||
if (route.startsWith("/")) {
|
||||
route = route.substring(1);
|
||||
}
|
||||
|
||||
var segments = splitBySlash(route);
|
||||
var results = [];
|
||||
|
||||
var specificity = '';
|
||||
|
||||
// a single slash (or "empty segment" is as specific as a static segment
|
||||
if (segments.length == 0) {
|
||||
specificity += '2';
|
||||
}
|
||||
|
||||
// The "specificity" of a path is used to determine which route is used when multiple routes match
|
||||
// a URL. Static segments (like "/foo") are the most specific, followed by dynamic segments (like
|
||||
// "/:id"). Star segments add no specificity. Segments at the start of the path are more specific
|
||||
// than proceeding ones.
|
||||
//
|
||||
// The code below uses place values to combine the different types of segments into a single
|
||||
// string that we can sort later. Each static segment is marked as a specificity of "2," each
|
||||
// dynamic segment is worth "1" specificity, and stars are worth "0" specificity.
|
||||
|
||||
var limit = segments.length - 1;
|
||||
for (var i = 0; i <= limit; i++) {
|
||||
var segment = segments[i], match;
|
||||
|
||||
if (isPresent(match = RegExpWrapper.firstMatch(paramMatcher, segment))) {
|
||||
results.push(new DynamicSegment(match[1]));
|
||||
specificity += '1';
|
||||
} else if (isPresent(match = RegExpWrapper.firstMatch(wildcardMatcher, segment))) {
|
||||
results.push(new StarSegment(match[1]));
|
||||
specificity += '0';
|
||||
} else if (segment == '...') {
|
||||
if (i < limit) {
|
||||
throw new BaseException(`Unexpected "..." before the end of the path for "${route}".`);
|
||||
}
|
||||
results.push(new ContinuationSegment());
|
||||
} else {
|
||||
results.push(new StaticSegment(segment));
|
||||
specificity += '2';
|
||||
}
|
||||
}
|
||||
|
||||
return {'segments': results, 'specificity': specificity};
|
||||
}
|
||||
|
||||
// this function is used to determine whether a route config path like `/foo/:id` collides with
|
||||
// `/foo/:name`
|
||||
function pathDslHash(segments: Segment[]): string {
|
||||
return segments.map((segment) => {
|
||||
if (segment instanceof StarSegment) {
|
||||
return '*';
|
||||
} else if (segment instanceof ContinuationSegment) {
|
||||
return '...';
|
||||
} else if (segment instanceof DynamicSegment) {
|
||||
return ':';
|
||||
} else if (segment instanceof StaticSegment) {
|
||||
return segment.path;
|
||||
}
|
||||
})
|
||||
.join('/');
|
||||
}
|
||||
|
||||
function splitBySlash(url: string): string[] {
|
||||
return url.split('/');
|
||||
}
|
||||
|
||||
var RESERVED_CHARS = RegExpWrapper.create('//|\\(|\\)|;|\\?|=');
|
||||
function assertPath(path: string) {
|
||||
if (StringWrapper.contains(path, '#')) {
|
||||
throw new BaseException(
|
||||
`Path "${path}" should not include "#". Use "HashLocationStrategy" instead.`);
|
||||
}
|
||||
var illegalCharacter = RegExpWrapper.firstMatch(RESERVED_CHARS, path);
|
||||
if (isPresent(illegalCharacter)) {
|
||||
throw new BaseException(
|
||||
`Path "${path}" contains "${illegalCharacter[0]}" which is not allowed in a route config.`);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Parses a URL string using a given matcher DSL, and generates URLs from param maps
|
||||
*/
|
||||
export class PathRecognizer {
|
||||
private _segments: Segment[];
|
||||
specificity: string;
|
||||
terminal: boolean = true;
|
||||
hash: string;
|
||||
|
||||
constructor(public path: string) {
|
||||
assertPath(path);
|
||||
var parsed = parsePathString(path);
|
||||
|
||||
this._segments = parsed['segments'];
|
||||
this.specificity = parsed['specificity'];
|
||||
this.hash = pathDslHash(this._segments);
|
||||
|
||||
var lastSegment = this._segments[this._segments.length - 1];
|
||||
this.terminal = !(lastSegment instanceof ContinuationSegment);
|
||||
}
|
||||
|
||||
recognize(beginningSegment: Url): {[key: string]: any} {
|
||||
var nextSegment = beginningSegment;
|
||||
var currentSegment: Url;
|
||||
var positionalParams = {};
|
||||
var captured = [];
|
||||
|
||||
for (var i = 0; i < this._segments.length; i += 1) {
|
||||
var segment = this._segments[i];
|
||||
|
||||
currentSegment = nextSegment;
|
||||
if (segment instanceof ContinuationSegment) {
|
||||
break;
|
||||
}
|
||||
|
||||
if (isPresent(currentSegment)) {
|
||||
// the star segment consumes all of the remaining URL, including matrix params
|
||||
if (segment instanceof StarSegment) {
|
||||
positionalParams[segment.name] = currentSegment.toString();
|
||||
captured.push(currentSegment.toString());
|
||||
nextSegment = null;
|
||||
break;
|
||||
}
|
||||
|
||||
captured.push(currentSegment.path);
|
||||
|
||||
if (segment instanceof DynamicSegment) {
|
||||
positionalParams[segment.name] = currentSegment.path;
|
||||
} else if (!segment.match(currentSegment.path)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
nextSegment = currentSegment.child;
|
||||
} else if (!segment.match('')) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
if (this.terminal && isPresent(nextSegment)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
var urlPath = captured.join('/');
|
||||
|
||||
var auxiliary;
|
||||
var urlParams;
|
||||
var allParams;
|
||||
if (isPresent(currentSegment)) {
|
||||
// If this is the root component, read query params. Otherwise, read matrix params.
|
||||
var paramsSegment = beginningSegment instanceof RootUrl ? beginningSegment : currentSegment;
|
||||
|
||||
allParams = isPresent(paramsSegment.params) ?
|
||||
StringMapWrapper.merge(paramsSegment.params, positionalParams) :
|
||||
positionalParams;
|
||||
|
||||
urlParams = serializeParams(paramsSegment.params);
|
||||
|
||||
|
||||
auxiliary = currentSegment.auxiliary;
|
||||
} else {
|
||||
allParams = positionalParams;
|
||||
auxiliary = [];
|
||||
urlParams = [];
|
||||
}
|
||||
return {urlPath, urlParams, allParams, auxiliary, nextSegment};
|
||||
}
|
||||
|
||||
|
||||
generate(params: {[key: string]: any}): {[key: string]: any} {
|
||||
var paramTokens = new TouchMap(params);
|
||||
|
||||
var path = [];
|
||||
|
||||
for (var i = 0; i < this._segments.length; i++) {
|
||||
let segment = this._segments[i];
|
||||
if (!(segment instanceof ContinuationSegment)) {
|
||||
path.push(segment.generate(paramTokens));
|
||||
}
|
||||
}
|
||||
var urlPath = path.join('/');
|
||||
|
||||
var nonPositionalParams = paramTokens.getUnused();
|
||||
var urlParams = serializeParams(nonPositionalParams);
|
||||
|
||||
return {urlPath, urlParams};
|
||||
}
|
||||
}
|
|
@ -1,6 +1,8 @@
|
|||
import {CONST, Type, isPresent} from 'angular2/src/facade/lang';
|
||||
import {RouteDefinition} from './route_definition';
|
||||
export {RouteDefinition} from './route_definition';
|
||||
import {RouteDefinition} from '../route_definition';
|
||||
import {RegexSerializer} from '../rules/route_paths/regex_route_path';
|
||||
|
||||
export {RouteDefinition} from '../route_definition';
|
||||
|
||||
/**
|
||||
* The `RouteConfig` decorator defines routes for a given component.
|
||||
|
@ -12,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.
|
||||
*
|
||||
|
@ -35,25 +56,20 @@ export class RouteConfig {
|
|||
* ```
|
||||
*/
|
||||
@CONST()
|
||||
export class Route implements RouteDefinition {
|
||||
data: {[key: string]: any};
|
||||
path: string;
|
||||
component: Type;
|
||||
name: string;
|
||||
useAsDefault: boolean;
|
||||
// added next three properties to work around https://github.com/Microsoft/TypeScript/issues/4107
|
||||
export class Route extends AbstractRoute {
|
||||
component: any;
|
||||
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
|
||||
}) {
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -78,20 +94,19 @@ export class Route implements RouteDefinition {
|
|||
* ```
|
||||
*/
|
||||
@CONST()
|
||||
export class AuxRoute implements RouteDefinition {
|
||||
data: {[key: string]: any} = null;
|
||||
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;
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -120,22 +135,20 @@ 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;
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -161,17 +174,18 @@ 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;
|
||||
}
|
||||
}
|
|
@ -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) {
|
|
@ -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';
|
||||
|
||||
|
||||
/**
|
|
@ -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});
|
||||
}
|
||||
|
|
|
@ -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.
|
||||
|
@ -14,6 +15,8 @@ import {CONST, Type} from 'angular2/src/facade/lang';
|
|||
export interface RouteDefinition {
|
||||
path?: string;
|
||||
aux?: string;
|
||||
regex?: string;
|
||||
serializer?: RegexSerializer;
|
||||
component?: Type | ComponentDefinition;
|
||||
loader?: Function;
|
||||
redirectTo?: any[];
|
||||
|
|
|
@ -24,9 +24,9 @@ import {
|
|||
AuxRoute,
|
||||
Redirect,
|
||||
RouteDefinition
|
||||
} from './route_config_impl';
|
||||
import {PathMatch, RedirectMatch, RouteMatch} from './route_recognizer';
|
||||
import {ComponentRecognizer} from './component_recognizer';
|
||||
} from './route_config/route_config_impl';
|
||||
import {PathMatch, RedirectMatch, RouteMatch} from './rules/rules';
|
||||
import {RuleSet} from './rules/rule_set';
|
||||
import {
|
||||
Instruction,
|
||||
ResolvedInstruction,
|
||||
|
@ -35,12 +35,20 @@ import {
|
|||
DefaultInstruction
|
||||
} from './instruction';
|
||||
|
||||
import {normalizeRouteConfig, assertComponentExists} from './route_config_nomalizer';
|
||||
import {parser, Url, 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);
|
||||
|
||||
|
||||
// A LinkItemArray is an array, which describes a set of routes
|
||||
// The items in the array are found in groups:
|
||||
// - the first item is the name of the route
|
||||
// - the next items are:
|
||||
// - an object containing parameters
|
||||
// - or an array describing an aux route
|
||||
// export type LinkRouteItem = string | Object;
|
||||
// export type LinkItem = LinkRouteItem | Array<LinkRouteItem>;
|
||||
// export type LinkItemArray = Array<LinkItem>;
|
||||
|
||||
/**
|
||||
* Token used to bind the component with the top-level {@link RouteConfig}s for the
|
||||
|
@ -78,7 +86,7 @@ export const ROUTER_PRIMARY_COMPONENT: OpaqueToken =
|
|||
*/
|
||||
@Injectable()
|
||||
export class RouteRegistry {
|
||||
private _rules = new Map<any, ComponentRecognizer>();
|
||||
private _rules = new Map<any, RuleSet>();
|
||||
|
||||
constructor(@Inject(ROUTER_PRIMARY_COMPONENT) private _rootComponent: Type) {}
|
||||
|
||||
|
@ -95,14 +103,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 +167,14 @@ 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<RouteMatch>[] =
|
||||
_aux ? componentRecognizer.recognizeAuxiliary(parsedUrl) :
|
||||
componentRecognizer.recognize(parsedUrl);
|
||||
_aux ? rules.recognizeAuxiliary(parsedUrl) : rules.recognize(parsedUrl);
|
||||
|
||||
var matchPromises: Promise<Instruction>[] = possibleMatches.map(
|
||||
(candidate: Promise<RouteMatch>) => candidate.then((candidate: RouteMatch) => {
|
||||
|
@ -184,9 +191,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,14 +366,14 @@ 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.`);
|
||||
}
|
||||
|
||||
let linkParamIndex = 0;
|
||||
let routeParams = {};
|
||||
let routeParams: {[key: string]: any} = {};
|
||||
|
||||
// first, recognize the primary route if one is provided
|
||||
if (linkParamIndex < linkParams.length && isString(linkParams[linkParamIndex])) {
|
||||
|
@ -382,8 +389,7 @@ export class RouteRegistry {
|
|||
linkParamIndex += 1;
|
||||
}
|
||||
}
|
||||
var routeRecognizer =
|
||||
(_aux ? componentRecognizer.auxNames : componentRecognizer.names).get(routeName);
|
||||
var routeRecognizer = (_aux ? rules.auxRulesByName : rules.rulesByName).get(routeName);
|
||||
|
||||
if (isBlank(routeRecognizer)) {
|
||||
throw new BaseException(
|
||||
|
@ -394,17 +400,17 @@ export class RouteRegistry {
|
|||
// we'll figure out the rest of the route when we resolve the instruction and
|
||||
// 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, convertUrlParamsToArray(generatedUrl.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 +448,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 +460,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.defaultRule)) {
|
||||
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.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 componentRecognizer.defaultRoute.handler.resolveComponentType().then(
|
||||
return rules.defaultRule.handler.resolveComponentType().then(
|
||||
(_) => this.generateDefault(componentCursor));
|
||||
});
|
||||
}
|
||||
|
@ -479,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: any[]) {
|
||||
var accumulation = [];
|
||||
linkParams.forEach(function(item: any) {
|
||||
if (isString(item)) {
|
||||
let strItem: string = item;
|
||||
return accumulation.concat(strItem.split('/'));
|
||||
var strItem: string = <string>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
|
||||
*/
|
||||
|
|
|
@ -9,10 +9,10 @@ import {
|
|||
ComponentInstruction,
|
||||
Instruction,
|
||||
} from './instruction';
|
||||
import {RouterOutlet} from './router_outlet';
|
||||
import {Location} from './location';
|
||||
import {getCanActivateHook} from './route_lifecycle_reflector';
|
||||
import {RouteDefinition} from './route_config_impl';
|
||||
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';
|
||||
|
||||
let _resolveToTrue = PromiseWrapper.resolve(true);
|
||||
let _resolveToFalse = PromiseWrapper.resolve(false);
|
||||
|
|
|
@ -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.
|
||||
|
|
|
@ -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';
|
||||
|
|
|
@ -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 {
|
|
@ -1,5 +1,5 @@
|
|||
import {Type} from 'angular2/src/facade/lang';
|
||||
import {RouteData} from './instruction';
|
||||
import {RouteData} from '../../instruction';
|
||||
|
||||
export interface RouteHandler {
|
||||
componentType: Type;
|
|
@ -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 {
|
|
@ -0,0 +1,271 @@
|
|||
import {RegExpWrapper, StringWrapper, isPresent, isBlank} from 'angular2/src/facade/lang';
|
||||
import {BaseException} from 'angular2/src/facade/exceptions';
|
||||
import {StringMapWrapper} from 'angular2/src/facade/collection';
|
||||
|
||||
import {TouchMap, normalizeString} from '../../utils';
|
||||
import {Url, RootUrl, convertUrlParamsToArray} from '../../url_parser';
|
||||
import {RoutePath, GeneratedUrl, MatchedUrl} from './route_path';
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* `ParamRoutePath`s are made up of `PathSegment`s, each of which can
|
||||
* match a segment of a URL. Different kind of `PathSegment`s match
|
||||
* URL segments in different ways...
|
||||
*/
|
||||
interface PathSegment {
|
||||
name: string;
|
||||
generate(params: TouchMap): string;
|
||||
match(path: string): boolean;
|
||||
specificity: string;
|
||||
hash: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Identified by a `...` URL segment. This indicates that the
|
||||
* Route will continue to be matched by child `Router`s.
|
||||
*/
|
||||
class ContinuationPathSegment implements PathSegment {
|
||||
name: string = '';
|
||||
specificity = '';
|
||||
hash = '...';
|
||||
generate(params: TouchMap): string { return ''; }
|
||||
match(path: string): boolean { return true; }
|
||||
}
|
||||
|
||||
/**
|
||||
* Identified by a string not starting with a `:` or `*`.
|
||||
* Only matches the URL segments that equal the segment path
|
||||
*/
|
||||
class StaticPathSegment implements PathSegment {
|
||||
name: string = '';
|
||||
specificity = '2';
|
||||
hash: string;
|
||||
constructor(public path: string) { this.hash = path; }
|
||||
match(path: string): boolean { return path == this.path; }
|
||||
generate(params: TouchMap): string { return this.path; }
|
||||
}
|
||||
|
||||
/**
|
||||
* Identified by a string starting with `:`. Indicates a segment
|
||||
* that can contain a value that will be extracted and provided to
|
||||
* a matching `Instruction`.
|
||||
*/
|
||||
class DynamicPathSegment implements PathSegment {
|
||||
static paramMatcher = /^:([^\/]+)$/g;
|
||||
specificity = '1';
|
||||
hash = ':';
|
||||
constructor(public name: string) {}
|
||||
match(path: string): boolean { return path.length > 0; }
|
||||
generate(params: TouchMap): string {
|
||||
if (!StringMapWrapper.contains(params.map, this.name)) {
|
||||
throw new BaseException(
|
||||
`Route generator for '${this.name}' was not included in parameters passed.`);
|
||||
}
|
||||
return normalizeString(params.get(this.name));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Identified by a string starting with `*` Indicates that all the following
|
||||
* segments match this route and that the value of these segments should
|
||||
* be provided to a matching `Instruction`.
|
||||
*/
|
||||
class StarPathSegment implements PathSegment {
|
||||
static wildcardMatcher = /^\*([^\/]+)$/g;
|
||||
specificity = '0';
|
||||
hash = '*';
|
||||
constructor(public name: string) {}
|
||||
match(path: string): boolean { return true; }
|
||||
generate(params: TouchMap): string { return normalizeString(params.get(this.name)); }
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses a URL string using a given matcher DSL, and generates URLs from param maps
|
||||
*/
|
||||
export class ParamRoutePath implements RoutePath {
|
||||
specificity: string;
|
||||
terminal: boolean = true;
|
||||
hash: string;
|
||||
|
||||
private _segments: PathSegment[];
|
||||
|
||||
/**
|
||||
* Takes a string representing the matcher DSL
|
||||
*/
|
||||
constructor(public routePath: string) {
|
||||
this._assertValidPath(routePath);
|
||||
|
||||
this._parsePathString(routePath);
|
||||
this.specificity = this._calculateSpecificity();
|
||||
this.hash = this._calculateHash();
|
||||
|
||||
var lastSegment = this._segments[this._segments.length - 1];
|
||||
this.terminal = !(lastSegment instanceof ContinuationPathSegment);
|
||||
}
|
||||
|
||||
matchUrl(url: Url): MatchedUrl {
|
||||
var nextUrlSegment = url;
|
||||
var currentUrlSegment: Url;
|
||||
var positionalParams = {};
|
||||
var captured: string[] = [];
|
||||
|
||||
for (var i = 0; i < this._segments.length; i += 1) {
|
||||
var pathSegment = this._segments[i];
|
||||
|
||||
currentUrlSegment = nextUrlSegment;
|
||||
if (pathSegment instanceof ContinuationPathSegment) {
|
||||
break;
|
||||
}
|
||||
|
||||
if (isPresent(currentUrlSegment)) {
|
||||
// the star segment consumes all of the remaining URL, including matrix params
|
||||
if (pathSegment instanceof StarPathSegment) {
|
||||
positionalParams[pathSegment.name] = currentUrlSegment.toString();
|
||||
captured.push(currentUrlSegment.toString());
|
||||
nextUrlSegment = null;
|
||||
break;
|
||||
}
|
||||
|
||||
captured.push(currentUrlSegment.path);
|
||||
|
||||
if (pathSegment instanceof DynamicPathSegment) {
|
||||
positionalParams[pathSegment.name] = currentUrlSegment.path;
|
||||
} else if (!pathSegment.match(currentUrlSegment.path)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
nextUrlSegment = currentUrlSegment.child;
|
||||
} else if (!pathSegment.match('')) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
if (this.terminal && isPresent(nextUrlSegment)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
var urlPath = captured.join('/');
|
||||
|
||||
var auxiliary = [];
|
||||
var urlParams = [];
|
||||
var allParams = positionalParams;
|
||||
if (isPresent(currentUrlSegment)) {
|
||||
// If this is the root component, read query params. Otherwise, read matrix params.
|
||||
var paramsSegment = url instanceof RootUrl ? url : currentUrlSegment;
|
||||
|
||||
if (isPresent(paramsSegment.params)) {
|
||||
allParams = StringMapWrapper.merge(paramsSegment.params, positionalParams);
|
||||
urlParams = convertUrlParamsToArray(paramsSegment.params);
|
||||
} else {
|
||||
allParams = positionalParams;
|
||||
}
|
||||
auxiliary = currentUrlSegment.auxiliary;
|
||||
}
|
||||
|
||||
return new MatchedUrl(urlPath, urlParams, allParams, auxiliary, nextUrlSegment);
|
||||
}
|
||||
|
||||
|
||||
generateUrl(params: {[key: string]: any}): GeneratedUrl {
|
||||
var paramTokens = new TouchMap(params);
|
||||
|
||||
var path = [];
|
||||
|
||||
for (var i = 0; i < this._segments.length; i++) {
|
||||
let segment = this._segments[i];
|
||||
if (!(segment instanceof ContinuationPathSegment)) {
|
||||
path.push(segment.generate(paramTokens));
|
||||
}
|
||||
}
|
||||
var urlPath = path.join('/');
|
||||
|
||||
var nonPositionalParams = paramTokens.getUnused();
|
||||
var urlParams = nonPositionalParams;
|
||||
|
||||
return new GeneratedUrl(urlPath, urlParams);
|
||||
}
|
||||
|
||||
|
||||
toString(): string { return this.routePath; }
|
||||
|
||||
private _parsePathString(routePath: string) {
|
||||
// normalize route as not starting with a "/". Recognition will
|
||||
// also normalize.
|
||||
if (routePath.startsWith("/")) {
|
||||
routePath = routePath.substring(1);
|
||||
}
|
||||
|
||||
var segmentStrings = routePath.split('/');
|
||||
this._segments = [];
|
||||
|
||||
var limit = segmentStrings.length - 1;
|
||||
for (var i = 0; i <= limit; i++) {
|
||||
var segment = segmentStrings[i], match;
|
||||
|
||||
if (isPresent(match = RegExpWrapper.firstMatch(DynamicPathSegment.paramMatcher, segment))) {
|
||||
this._segments.push(new DynamicPathSegment(match[1]));
|
||||
} else if (isPresent(
|
||||
match = RegExpWrapper.firstMatch(StarPathSegment.wildcardMatcher, segment))) {
|
||||
this._segments.push(new StarPathSegment(match[1]));
|
||||
} else if (segment == '...') {
|
||||
if (i < limit) {
|
||||
throw new BaseException(
|
||||
`Unexpected "..." before the end of the path for "${routePath}".`);
|
||||
}
|
||||
this._segments.push(new ContinuationPathSegment());
|
||||
} else {
|
||||
this._segments.push(new StaticPathSegment(segment));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private _calculateSpecificity(): string {
|
||||
// The "specificity" of a path is used to determine which route is used when multiple routes
|
||||
// match
|
||||
// a URL. Static segments (like "/foo") are the most specific, followed by dynamic segments
|
||||
// (like
|
||||
// "/:id"). Star segments add no specificity. Segments at the start of the path are more
|
||||
// specific
|
||||
// than proceeding ones.
|
||||
//
|
||||
// The code below uses place values to combine the different types of segments into a single
|
||||
// string that we can sort later. Each static segment is marked as a specificity of "2," each
|
||||
// dynamic segment is worth "1" specificity, and stars are worth "0" specificity.
|
||||
var i, length = this._segments.length, specificity;
|
||||
if (length == 0) {
|
||||
// a single slash (or "empty segment" is as specific as a static segment
|
||||
specificity += '2';
|
||||
} else {
|
||||
specificity = '';
|
||||
for (i = 0; i < length; i++) {
|
||||
specificity += this._segments[i].specificity;
|
||||
}
|
||||
}
|
||||
return specificity;
|
||||
}
|
||||
|
||||
private _calculateHash(): string {
|
||||
// this function is used to determine whether a route config path like `/foo/:id` collides with
|
||||
// `/foo/:name`
|
||||
var i, length = this._segments.length;
|
||||
var hashParts = [];
|
||||
for (i = 0; i < length; i++) {
|
||||
hashParts.push(this._segments[i].hash);
|
||||
}
|
||||
return hashParts.join('/');
|
||||
}
|
||||
|
||||
private _assertValidPath(path: string) {
|
||||
if (StringWrapper.contains(path, '#')) {
|
||||
throw new BaseException(
|
||||
`Path "${path}" should not include "#". Use "HashLocationStrategy" instead.`);
|
||||
}
|
||||
var illegalCharacter = RegExpWrapper.firstMatch(ParamRoutePath.RESERVED_CHARS, path);
|
||||
if (isPresent(illegalCharacter)) {
|
||||
throw new BaseException(
|
||||
`Path "${path}" contains "${illegalCharacter[0]}" which is not allowed in a route config.`);
|
||||
}
|
||||
}
|
||||
static RESERVED_CHARS = RegExpWrapper.create('//|\\(|\\)|;|\\?|=');
|
||||
}
|
|
@ -0,0 +1,40 @@
|
|||
import {RegExpWrapper, RegExpMatcherWrapper, isBlank} from 'angular2/src/facade/lang';
|
||||
import {Url, RootUrl} from '../../url_parser';
|
||||
import {RoutePath, GeneratedUrl, MatchedUrl} from './route_path';
|
||||
|
||||
|
||||
export interface RegexSerializer { (params: {[key: string]: any}): GeneratedUrl; }
|
||||
|
||||
export class RegexRoutePath implements RoutePath {
|
||||
public hash: string;
|
||||
public terminal: boolean = true;
|
||||
public specificity: string = '2';
|
||||
|
||||
private _regex: RegExp;
|
||||
|
||||
constructor(private _reString: string, private _serializer: RegexSerializer) {
|
||||
this.hash = this._reString;
|
||||
this._regex = RegExpWrapper.create(this._reString);
|
||||
}
|
||||
|
||||
matchUrl(url: Url): MatchedUrl {
|
||||
var urlPath = url.toString();
|
||||
var params: {[key: string]: string} = {};
|
||||
var matcher = RegExpWrapper.matcher(this._regex, urlPath);
|
||||
var match = RegExpMatcherWrapper.next(matcher);
|
||||
|
||||
if (isBlank(match)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
for (let i = 0; i < match.length; i += 1) {
|
||||
params[i.toString()] = match[i];
|
||||
}
|
||||
|
||||
return new MatchedUrl(urlPath, [], params, [], null);
|
||||
}
|
||||
|
||||
generateUrl(params: {[key: string]: any}): GeneratedUrl { return this._serializer(params); }
|
||||
|
||||
toString() { return this._reString; }
|
||||
}
|
|
@ -0,0 +1,20 @@
|
|||
import {Url} from '../../url_parser';
|
||||
|
||||
export class MatchedUrl {
|
||||
constructor(public urlPath: string, public urlParams: string[],
|
||||
public allParams: {[key: string]: any}, public auxiliary: Url[], public rest: Url) {}
|
||||
}
|
||||
|
||||
|
||||
export class GeneratedUrl {
|
||||
constructor(public urlPath: string, public urlParams: {[key: string]: any}) {}
|
||||
}
|
||||
|
||||
export interface RoutePath {
|
||||
specificity: string;
|
||||
terminal: boolean;
|
||||
hash: string;
|
||||
matchUrl(url: Url): MatchedUrl;
|
||||
generateUrl(params: {[key: string]: any}): GeneratedUrl;
|
||||
toString(): string;
|
||||
}
|
|
@ -0,0 +1,191 @@
|
|||
import {isBlank, isPresent, isFunction} from 'angular2/src/facade/lang';
|
||||
import {BaseException, WrappedException} from 'angular2/src/facade/exceptions';
|
||||
import {Map, MapWrapper, ListWrapper, StringMapWrapper} from 'angular2/src/facade/collection';
|
||||
import {PromiseWrapper} from 'angular2/src/facade/async';
|
||||
|
||||
import {AbstractRule, RouteRule, RedirectRule, RouteMatch, PathMatch} from './rules';
|
||||
import {
|
||||
Route,
|
||||
AsyncRoute,
|
||||
AuxRoute,
|
||||
Redirect,
|
||||
RouteDefinition
|
||||
} from '../route_config/route_config_impl';
|
||||
|
||||
import {AsyncRouteHandler} from './route_handlers/async_route_handler';
|
||||
import {SyncRouteHandler} from './route_handlers/sync_route_handler';
|
||||
|
||||
import {RoutePath} from './route_paths/route_path';
|
||||
import {ParamRoutePath} from './route_paths/param_route_path';
|
||||
import {RegexRoutePath} from './route_paths/regex_route_path';
|
||||
|
||||
import {Url} from '../url_parser';
|
||||
import {ComponentInstruction} from '../instruction';
|
||||
|
||||
|
||||
/**
|
||||
* A `RuleSet` is responsible for recognizing routes for a particular component.
|
||||
* It is consumed by `RouteRegistry`, which knows how to recognize an entire hierarchy of
|
||||
* components.
|
||||
*/
|
||||
export class RuleSet {
|
||||
rulesByName = new Map<string, RouteRule>();
|
||||
|
||||
// map from name to rule
|
||||
auxRulesByName = new Map<string, RouteRule>();
|
||||
|
||||
// map from starting path to rule
|
||||
auxRulesByPath = new Map<string, RouteRule>();
|
||||
|
||||
// TODO: optimize this into a trie
|
||||
rules: AbstractRule[] = [];
|
||||
|
||||
// the rule to use automatically when recognizing or generating from this rule set
|
||||
defaultRule: RouteRule = null;
|
||||
|
||||
/**
|
||||
* Configure additional rules in this rule set from a route definition
|
||||
* @returns {boolean} true if the config is terminal
|
||||
*/
|
||||
config(config: RouteDefinition): boolean {
|
||||
let handler;
|
||||
|
||||
if (isPresent(config.name) && config.name[0].toUpperCase() != config.name[0]) {
|
||||
let suggestedName = config.name[0].toUpperCase() + config.name.substring(1);
|
||||
throw new BaseException(
|
||||
`Route "${config.path}" with name "${config.name}" does not begin with an uppercase letter. Route names should be CamelCase like "${suggestedName}".`);
|
||||
}
|
||||
|
||||
if (config instanceof AuxRoute) {
|
||||
handler = new SyncRouteHandler(config.component, config.data);
|
||||
let routePath = this._getRoutePath(config);
|
||||
let auxRule = new RouteRule(routePath, handler);
|
||||
this.auxRulesByPath.set(routePath.toString(), auxRule);
|
||||
if (isPresent(config.name)) {
|
||||
this.auxRulesByName.set(config.name, auxRule);
|
||||
}
|
||||
return auxRule.terminal;
|
||||
}
|
||||
|
||||
let useAsDefault = false;
|
||||
|
||||
if (config instanceof Redirect) {
|
||||
let routePath = this._getRoutePath(config);
|
||||
let redirector = new RedirectRule(routePath, config.redirectTo);
|
||||
this._assertNoHashCollision(redirector.hash, config.path);
|
||||
this.rules.push(redirector);
|
||||
return true;
|
||||
}
|
||||
|
||||
if (config instanceof Route) {
|
||||
handler = new SyncRouteHandler(config.component, config.data);
|
||||
useAsDefault = isPresent(config.useAsDefault) && config.useAsDefault;
|
||||
} else if (config instanceof AsyncRoute) {
|
||||
handler = new AsyncRouteHandler(config.loader, config.data);
|
||||
useAsDefault = isPresent(config.useAsDefault) && config.useAsDefault;
|
||||
}
|
||||
let routePath = this._getRoutePath(config);
|
||||
let newRule = new RouteRule(routePath, handler);
|
||||
|
||||
this._assertNoHashCollision(newRule.hash, config.path);
|
||||
|
||||
if (useAsDefault) {
|
||||
if (isPresent(this.defaultRule)) {
|
||||
throw new BaseException(`Only one route can be default`);
|
||||
}
|
||||
this.defaultRule = newRule;
|
||||
}
|
||||
|
||||
this.rules.push(newRule);
|
||||
if (isPresent(config.name)) {
|
||||
this.rulesByName.set(config.name, newRule);
|
||||
}
|
||||
return newRule.terminal;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Given a URL, returns a list of `RouteMatch`es, which are partial recognitions for some route.
|
||||
*/
|
||||
recognize(urlParse: Url): Promise<RouteMatch>[] {
|
||||
var solutions = [];
|
||||
|
||||
this.rules.forEach((routeRecognizer: AbstractRule) => {
|
||||
var pathMatch = routeRecognizer.recognize(urlParse);
|
||||
|
||||
if (isPresent(pathMatch)) {
|
||||
solutions.push(pathMatch);
|
||||
}
|
||||
});
|
||||
|
||||
// handle cases where we are routing just to an aux route
|
||||
if (solutions.length == 0 && isPresent(urlParse) && urlParse.auxiliary.length > 0) {
|
||||
return [PromiseWrapper.resolve(new PathMatch(null, null, urlParse.auxiliary))];
|
||||
}
|
||||
|
||||
return solutions;
|
||||
}
|
||||
|
||||
recognizeAuxiliary(urlParse: Url): Promise<RouteMatch>[] {
|
||||
var routeRecognizer: RouteRule = this.auxRulesByPath.get(urlParse.path);
|
||||
if (isPresent(routeRecognizer)) {
|
||||
return [routeRecognizer.recognize(urlParse)];
|
||||
}
|
||||
|
||||
return [PromiseWrapper.resolve(null)];
|
||||
}
|
||||
|
||||
hasRoute(name: string): boolean { return this.rulesByName.has(name); }
|
||||
|
||||
componentLoaded(name: string): boolean {
|
||||
return this.hasRoute(name) && isPresent(this.rulesByName.get(name).handler.componentType);
|
||||
}
|
||||
|
||||
loadComponent(name: string): Promise<any> {
|
||||
return this.rulesByName.get(name).handler.resolveComponentType();
|
||||
}
|
||||
|
||||
generate(name: string, params: any): ComponentInstruction {
|
||||
var rule: RouteRule = this.rulesByName.get(name);
|
||||
if (isBlank(rule)) {
|
||||
return null;
|
||||
}
|
||||
return rule.generate(params);
|
||||
}
|
||||
|
||||
generateAuxiliary(name: string, params: any): ComponentInstruction {
|
||||
var rule: RouteRule = this.auxRulesByName.get(name);
|
||||
if (isBlank(rule)) {
|
||||
return null;
|
||||
}
|
||||
return rule.generate(params);
|
||||
}
|
||||
|
||||
private _assertNoHashCollision(hash: string, path) {
|
||||
this.rules.forEach((rule) => {
|
||||
if (hash == rule.hash) {
|
||||
throw new BaseException(
|
||||
`Configuration '${path}' conflicts with existing route '${rule.path}'`);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private _getRoutePath(config: RouteDefinition): RoutePath {
|
||||
if (isPresent(config.regex)) {
|
||||
if (isFunction(config.serializer)) {
|
||||
return new RegexRoutePath(config.regex, config.serializer);
|
||||
} else {
|
||||
throw new BaseException(
|
||||
`Route provides a regex property, '${config.regex}', but no serializer property`);
|
||||
}
|
||||
}
|
||||
if (isPresent(config.path)) {
|
||||
// Auxiliary routes do not have a slash at the start
|
||||
let path = (config instanceof AuxRoute && config.path.startsWith('/')) ?
|
||||
config.path.substring(1) :
|
||||
config.path;
|
||||
return new ParamRoutePath(path);
|
||||
}
|
||||
throw new BaseException('Route must provide either a path or regex property');
|
||||
}
|
||||
}
|
|
@ -3,22 +3,16 @@ 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 {Url} from './url_parser';
|
||||
import {ComponentInstruction} from './instruction';
|
||||
import {PathRecognizer} from './path_recognizer';
|
||||
import {RouteHandler} from './route_handlers/route_handler';
|
||||
import {Url, convertUrlParamsToArray} from '../url_parser';
|
||||
import {ComponentInstruction} from '../instruction';
|
||||
import {RoutePath} from './route_paths/route_path';
|
||||
import {GeneratedUrl} from './route_paths/route_path';
|
||||
|
||||
|
||||
// RouteMatch objects hold information about a match between a rule and a URL
|
||||
export abstract class RouteMatch {}
|
||||
|
||||
export interface AbstractRecognizer {
|
||||
hash: string;
|
||||
path: string;
|
||||
recognize(beginningSegment: Url): Promise<RouteMatch>;
|
||||
generate(params: {[key: string]: any}): ComponentInstruction;
|
||||
}
|
||||
|
||||
|
||||
export class PathMatch extends RouteMatch {
|
||||
constructor(public instruction: ComponentInstruction, public remaining: Url,
|
||||
public remainingAux: Url[]) {
|
||||
|
@ -26,26 +20,34 @@ export class PathMatch extends RouteMatch {
|
|||
}
|
||||
}
|
||||
|
||||
|
||||
export class RedirectMatch extends RouteMatch {
|
||||
constructor(public redirectTo: any[], public specificity) { super(); }
|
||||
}
|
||||
|
||||
export class RedirectRecognizer implements AbstractRecognizer {
|
||||
private _pathRecognizer: PathRecognizer;
|
||||
// Rules are responsible for recognizing URL segments and generating instructions
|
||||
export interface AbstractRule {
|
||||
hash: string;
|
||||
path: string;
|
||||
recognize(beginningSegment: Url): Promise<RouteMatch>;
|
||||
generate(params: {[key: string]: any}): ComponentInstruction;
|
||||
}
|
||||
|
||||
export class RedirectRule implements AbstractRule {
|
||||
public hash: string;
|
||||
|
||||
constructor(public path: string, public redirectTo: any[]) {
|
||||
this._pathRecognizer = new PathRecognizer(path);
|
||||
constructor(private _pathRecognizer: RoutePath, public redirectTo: any[]) {
|
||||
this.hash = this._pathRecognizer.hash;
|
||||
}
|
||||
|
||||
get path() { return this._pathRecognizer.toString(); }
|
||||
set path(val) { throw new BaseException('you cannot set the path of a RedirectRule directly'); }
|
||||
|
||||
/**
|
||||
* Returns `null` or a `ParsedUrl` representing the new path to match
|
||||
*/
|
||||
recognize(beginningSegment: Url): Promise<RouteMatch> {
|
||||
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);
|
||||
|
@ -58,45 +60,45 @@ 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;
|
||||
terminal: boolean;
|
||||
hash: string;
|
||||
|
||||
private _cache: Map<string, ComponentInstruction> = new Map<string, ComponentInstruction>();
|
||||
private _pathRecognizer: PathRecognizer;
|
||||
|
||||
// TODO: cache component instruction instances by params and by ParsedUrl instance
|
||||
|
||||
constructor(public path: string, public handler: RouteHandler) {
|
||||
this._pathRecognizer = new PathRecognizer(path);
|
||||
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._routePath.toString(); }
|
||||
set path(val) { throw new BaseException('you cannot set the path of a RouteRule directly'); }
|
||||
|
||||
recognize(beginningSegment: Url): Promise<RouteMatch> {
|
||||
var res = this._pathRecognizer.recognize(beginningSegment);
|
||||
var res = this._routePath.matchUrl(beginningSegment);
|
||||
if (isBlank(res)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return this.handler.resolveComponentType().then((_) => {
|
||||
var componentInstruction =
|
||||
this._getInstruction(res['urlPath'], res['urlParams'], res['allParams']);
|
||||
return new PathMatch(componentInstruction, res['nextSegment'], res['auxiliary']);
|
||||
var componentInstruction = this._getInstruction(res.urlPath, res.urlParams, res.allParams);
|
||||
return new PathMatch(componentInstruction, res.rest, res.auxiliary);
|
||||
});
|
||||
}
|
||||
|
||||
generate(params: {[key: string]: any}): ComponentInstruction {
|
||||
var generated = this._pathRecognizer.generate(params);
|
||||
var urlPath = generated['urlPath'];
|
||||
var urlParams = generated['urlParams'];
|
||||
return this._getInstruction(urlPath, urlParams, params);
|
||||
var generated = this._routePath.generateUrl(params);
|
||||
var urlPath = generated.urlPath;
|
||||
var urlParams = generated.urlParams;
|
||||
return this._getInstruction(urlPath, convertUrlParamsToArray(urlParams), params);
|
||||
}
|
||||
|
||||
generateComponentPathValues(params: {[key: string]: any}): {[key: string]: any} {
|
||||
return this._pathRecognizer.generate(params);
|
||||
generateComponentPathValues(params: {[key: string]: any}): GeneratedUrl {
|
||||
return this._routePath.generateUrl(params);
|
||||
}
|
||||
|
||||
private _getInstruction(urlPath: string, urlParams: string[],
|
||||
|
@ -104,8 +106,7 @@ export class RouteRecognizer implements AbstractRecognizer {
|
|||
if (isBlank(this.handler.componentType)) {
|
||||
throw new BaseException(`Tried to get instruction before the type was loaded.`);
|
||||
}
|
||||
|
||||
var hashKey = urlPath + '?' + urlParams.join('?');
|
||||
var hashKey = urlPath + '?' + urlParams.join('&');
|
||||
if (this._cache.has(hashKey)) {
|
||||
return this._cache.get(hashKey);
|
||||
}
|
|
@ -2,13 +2,28 @@ 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[] {
|
||||
var paramsArray = [];
|
||||
if (isBlank(urlParams)) {
|
||||
return [];
|
||||
}
|
||||
StringMapWrapper.forEach(
|
||||
urlParams, (value, key) => { paramsArray.push((value === true) ? key : key + '=' + value); });
|
||||
return paramsArray;
|
||||
}
|
||||
|
||||
// Convert an object of url parameters into a string that can be used in an URL
|
||||
export function serializeParams(urlParams: {[key: string]: any}, joiner = '&'): string {
|
||||
return convertUrlParamsToArray(urlParams).join(joiner);
|
||||
}
|
||||
|
||||
/**
|
||||
* This class represents a parsed URL
|
||||
*/
|
||||
export class Url {
|
||||
constructor(public path: string, public child: Url = null,
|
||||
public auxiliary: Url[] = CONST_EXPR([]),
|
||||
public params: {[key: string]: any} = null) {}
|
||||
public params: {[key: string]: any} = CONST_EXPR({})) {}
|
||||
|
||||
toString(): string {
|
||||
return this.path + this._matrixParamsToString() + this._auxToString() + this._childString();
|
||||
|
@ -24,11 +39,11 @@ export class Url {
|
|||
}
|
||||
|
||||
private _matrixParamsToString(): string {
|
||||
if (isBlank(this.params)) {
|
||||
return '';
|
||||
var paramString = serializeParams(this.params, ';');
|
||||
if (paramString.length > 0) {
|
||||
return ';' + paramString;
|
||||
}
|
||||
|
||||
return ';' + serializeParams(this.params).join(';');
|
||||
return '';
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
|
@ -52,7 +67,7 @@ export class RootUrl extends Url {
|
|||
return '';
|
||||
}
|
||||
|
||||
return '?' + serializeParams(this.params).join('&');
|
||||
return '?' + serializeParams(this.params);
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -91,7 +106,7 @@ export class UrlParser {
|
|||
}
|
||||
|
||||
// segment + (aux segments) + (query params)
|
||||
parseRoot(): Url {
|
||||
parseRoot(): RootUrl {
|
||||
if (this.peekStartsWith('/')) {
|
||||
this.capture('/');
|
||||
}
|
||||
|
@ -200,18 +215,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();
|
|
@ -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();
|
||||
}
|
||||
}
|
|
@ -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 {
|
||||
|
|
|
@ -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([
|
||||
|
|
|
@ -3,7 +3,7 @@ import {
|
|||
PlatformLocation,
|
||||
UrlChangeEvent,
|
||||
UrlChangeListener
|
||||
} from 'angular2/src/router/platform_location';
|
||||
} from 'angular2/src/router/location/platform_location';
|
||||
import {
|
||||
FnArg,
|
||||
UiArguments,
|
||||
|
|
|
@ -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';
|
||||
|
||||
|
|
|
@ -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';
|
|
@ -15,8 +15,8 @@ import {
|
|||
import {Injector, provide} from 'angular2/core';
|
||||
import {CONST_EXPR} from 'angular2/src/facade/lang';
|
||||
|
||||
import {parseRouterLinkExpression} from 'angular2/src/router/router_link_transform';
|
||||
import {Unparser} from '../core/change_detection/parser/unparser';
|
||||
import {parseRouterLinkExpression} from 'angular2/src/router/directives/router_link_transform';
|
||||
import {Unparser} from '../../core/change_detection/parser/unparser';
|
||||
import {Parser} from 'angular2/src/core/change_detection/parser/parser';
|
||||
|
||||
export function main() {
|
|
@ -20,7 +20,12 @@ import {DOM} from 'angular2/src/platform/dom/dom_adapter';
|
|||
import {Console} from 'angular2/src/core/console';
|
||||
import {provide, ViewChild, AfterViewInit} from 'angular2/core';
|
||||
import {DOCUMENT} from 'angular2/src/platform/dom/dom_tokens';
|
||||
import {RouteConfig, Route, Redirect, AuxRoute} from 'angular2/src/router/route_config_decorator';
|
||||
import {
|
||||
RouteConfig,
|
||||
Route,
|
||||
Redirect,
|
||||
AuxRoute
|
||||
} from 'angular2/src/router/route_config/route_config_decorator';
|
||||
import {PromiseWrapper} from 'angular2/src/facade/async';
|
||||
import {BaseException, WrappedException} from 'angular2/src/facade/exceptions';
|
||||
import {
|
||||
|
|
|
@ -19,7 +19,12 @@ import {By} from 'angular2/platform/common_dom';
|
|||
import {provide, Component, Injector, Inject} from 'angular2/core';
|
||||
|
||||
import {Router, ROUTER_DIRECTIVES, RouteParams, RouteData, Location} from 'angular2/router';
|
||||
import {RouteConfig, Route, AuxRoute, Redirect} from 'angular2/src/router/route_config_decorator';
|
||||
import {
|
||||
RouteConfig,
|
||||
Route,
|
||||
AuxRoute,
|
||||
Redirect
|
||||
} from 'angular2/src/router/route_config/route_config_decorator';
|
||||
|
||||
import {specs, compile, TEST_ROUTER_PROVIDERS, clickOnElement, getHref} from '../util';
|
||||
import {BaseException} from 'angular2/src/facade/exceptions';
|
||||
|
|
|
@ -31,7 +31,7 @@ import {
|
|||
AuxRoute,
|
||||
AsyncRoute,
|
||||
Redirect
|
||||
} from 'angular2/src/router/route_config_decorator';
|
||||
} from 'angular2/src/router/route_config/route_config_decorator';
|
||||
|
||||
import {
|
||||
OnActivate,
|
||||
|
@ -40,7 +40,7 @@ import {
|
|||
CanDeactivate,
|
||||
CanReuse
|
||||
} from 'angular2/src/router/interfaces';
|
||||
import {CanActivate} from 'angular2/src/router/lifecycle_annotations';
|
||||
import {CanActivate} from 'angular2/src/router/lifecycle/lifecycle_annotations';
|
||||
import {ComponentInstruction} from 'angular2/src/router/instruction';
|
||||
|
||||
|
||||
|
|
|
@ -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';
|
||||
|
||||
|
|
|
@ -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';
|
||||
|
|
|
@ -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() {
|
||||
|
|
|
@ -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';
|
||||
|
|
|
@ -14,10 +14,10 @@ import {
|
|||
|
||||
import {Injector, provide} from 'angular2/core';
|
||||
|
||||
import {PlatformLocation} from 'angular2/src/router/platform_location';
|
||||
import {APP_BASE_HREF} from 'angular2/src/router/location_strategy';
|
||||
import {HashLocationStrategy} from 'angular2/src/router/hash_location_strategy';
|
||||
import {SpyPlatformLocation} from './spies';
|
||||
import {PlatformLocation} from 'angular2/src/router/location/platform_location';
|
||||
import {APP_BASE_HREF} from 'angular2/src/router/location/location_strategy';
|
||||
import {HashLocationStrategy} from 'angular2/src/router/location/hash_location_strategy';
|
||||
import {SpyPlatformLocation} from '../spies';
|
||||
|
||||
export function main() {
|
||||
describe('HashLocationStrategy', () => {
|
|
@ -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() {
|
|
@ -15,10 +15,10 @@ import {
|
|||
import {Injector, provide} from 'angular2/core';
|
||||
import {CONST_EXPR} from 'angular2/src/facade/lang';
|
||||
|
||||
import {PlatformLocation} from 'angular2/src/router/platform_location';
|
||||
import {LocationStrategy, APP_BASE_HREF} from 'angular2/src/router/location_strategy';
|
||||
import {PathLocationStrategy} from 'angular2/src/router/path_location_strategy';
|
||||
import {SpyPlatformLocation} from './spies';
|
||||
import {PlatformLocation} from 'angular2/src/router/location/platform_location';
|
||||
import {LocationStrategy, APP_BASE_HREF} from 'angular2/src/router/location/location_strategy';
|
||||
import {PathLocationStrategy} from 'angular2/src/router/location/path_location_strategy';
|
||||
import {SpyPlatformLocation} from '../spies';
|
||||
|
||||
export function main() {
|
||||
describe('PathLocationStrategy', () => {
|
|
@ -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 {
|
|
@ -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() {
|
||||
|
|
|
@ -18,10 +18,15 @@ import {ListWrapper} from 'angular2/src/facade/collection';
|
|||
|
||||
import {Router, RootRouter} from 'angular2/src/router/router';
|
||||
import {SpyLocation} from 'angular2/src/mock/location_mock';
|
||||
import {Location} from 'angular2/src/router/location';
|
||||
import {Location} from 'angular2/src/router/location/location';
|
||||
|
||||
import {RouteRegistry, ROUTER_PRIMARY_COMPONENT} from 'angular2/src/router/route_registry';
|
||||
import {RouteConfig, AsyncRoute, Route, Redirect} from 'angular2/src/router/route_config_decorator';
|
||||
import {
|
||||
RouteConfig,
|
||||
AsyncRoute,
|
||||
Route,
|
||||
Redirect
|
||||
} from 'angular2/src/router/route_config/route_config_decorator';
|
||||
import {DirectiveResolver} from 'angular2/src/core/linker/directive_resolver';
|
||||
|
||||
import {provide} from 'angular2/core';
|
||||
|
|
|
@ -10,93 +10,93 @@ import {
|
|||
SpyObject
|
||||
} from 'angular2/testing_internal';
|
||||
|
||||
import {PathRecognizer} from 'angular2/src/router/path_recognizer';
|
||||
import {parser, Url, RootUrl} from 'angular2/src/router/url_parser';
|
||||
import {ParamRoutePath} from 'angular2/src/router/rules/route_paths/param_route_path';
|
||||
import {parser, Url} from 'angular2/src/router/url_parser';
|
||||
|
||||
export function main() {
|
||||
describe('PathRecognizer', () => {
|
||||
|
||||
it('should throw when given an invalid path', () => {
|
||||
expect(() => new PathRecognizer('/hi#'))
|
||||
expect(() => new ParamRoutePath('/hi#'))
|
||||
.toThrowError(`Path "/hi#" should not include "#". Use "HashLocationStrategy" instead.`);
|
||||
expect(() => new PathRecognizer('hi?'))
|
||||
expect(() => new ParamRoutePath('hi?'))
|
||||
.toThrowError(`Path "hi?" contains "?" which is not allowed in a route config.`);
|
||||
expect(() => new PathRecognizer('hi;'))
|
||||
expect(() => new ParamRoutePath('hi;'))
|
||||
.toThrowError(`Path "hi;" contains ";" which is not allowed in a route config.`);
|
||||
expect(() => new PathRecognizer('hi='))
|
||||
expect(() => new ParamRoutePath('hi='))
|
||||
.toThrowError(`Path "hi=" contains "=" which is not allowed in a route config.`);
|
||||
expect(() => new PathRecognizer('hi('))
|
||||
expect(() => new ParamRoutePath('hi('))
|
||||
.toThrowError(`Path "hi(" contains "(" which is not allowed in a route config.`);
|
||||
expect(() => new PathRecognizer('hi)'))
|
||||
expect(() => new ParamRoutePath('hi)'))
|
||||
.toThrowError(`Path "hi)" contains ")" which is not allowed in a route config.`);
|
||||
expect(() => new PathRecognizer('hi//there'))
|
||||
expect(() => new ParamRoutePath('hi//there'))
|
||||
.toThrowError(`Path "hi//there" contains "//" which is not allowed in a route config.`);
|
||||
});
|
||||
|
||||
describe('querystring params', () => {
|
||||
it('should parse querystring params so long as the recognizer is a root', () => {
|
||||
var rec = new PathRecognizer('/hello/there');
|
||||
var rec = new ParamRoutePath('/hello/there');
|
||||
var url = parser.parse('/hello/there?name=igor');
|
||||
var match = rec.recognize(url);
|
||||
expect(match['allParams']).toEqual({'name': 'igor'});
|
||||
var match = rec.matchUrl(url);
|
||||
expect(match.allParams).toEqual({'name': 'igor'});
|
||||
});
|
||||
|
||||
it('should return a combined map of parameters with the param expected in the URL path',
|
||||
() => {
|
||||
var rec = new PathRecognizer('/hello/:name');
|
||||
var rec = new ParamRoutePath('/hello/:name');
|
||||
var url = parser.parse('/hello/paul?topic=success');
|
||||
var match = rec.recognize(url);
|
||||
expect(match['allParams']).toEqual({'name': 'paul', 'topic': 'success'});
|
||||
var match = rec.matchUrl(url);
|
||||
expect(match.allParams).toEqual({'name': 'paul', 'topic': 'success'});
|
||||
});
|
||||
});
|
||||
|
||||
describe('matrix params', () => {
|
||||
it('should be parsed along with dynamic paths', () => {
|
||||
var rec = new PathRecognizer('/hello/:id');
|
||||
var rec = new ParamRoutePath('/hello/:id');
|
||||
var url = new Url('hello', new Url('matias', null, null, {'key': 'value'}));
|
||||
var match = rec.recognize(url);
|
||||
expect(match['allParams']).toEqual({'id': 'matias', 'key': 'value'});
|
||||
var match = rec.matchUrl(url);
|
||||
expect(match.allParams).toEqual({'id': 'matias', 'key': 'value'});
|
||||
});
|
||||
|
||||
it('should be parsed on a static path', () => {
|
||||
var rec = new PathRecognizer('/person');
|
||||
var rec = new ParamRoutePath('/person');
|
||||
var url = new Url('person', null, null, {'name': 'dave'});
|
||||
var match = rec.recognize(url);
|
||||
expect(match['allParams']).toEqual({'name': 'dave'});
|
||||
var match = rec.matchUrl(url);
|
||||
expect(match.allParams).toEqual({'name': 'dave'});
|
||||
});
|
||||
|
||||
it('should be ignored on a wildcard segment', () => {
|
||||
var rec = new PathRecognizer('/wild/*everything');
|
||||
var rec = new ParamRoutePath('/wild/*everything');
|
||||
var url = parser.parse('/wild/super;variable=value');
|
||||
var match = rec.recognize(url);
|
||||
expect(match['allParams']).toEqual({'everything': 'super;variable=value'});
|
||||
var match = rec.matchUrl(url);
|
||||
expect(match.allParams).toEqual({'everything': 'super;variable=value'});
|
||||
});
|
||||
|
||||
it('should set matrix param values to true when no value is present', () => {
|
||||
var rec = new PathRecognizer('/path');
|
||||
var rec = new ParamRoutePath('/path');
|
||||
var url = new Url('path', null, null, {'one': true, 'two': true, 'three': '3'});
|
||||
var match = rec.recognize(url);
|
||||
expect(match['allParams']).toEqual({'one': true, 'two': true, 'three': '3'});
|
||||
var match = rec.matchUrl(url);
|
||||
expect(match.allParams).toEqual({'one': true, 'two': true, 'three': '3'});
|
||||
});
|
||||
|
||||
it('should be parsed on the final segment of the path', () => {
|
||||
var rec = new PathRecognizer('/one/two/three');
|
||||
var rec = new ParamRoutePath('/one/two/three');
|
||||
|
||||
var three = new Url('three', null, null, {'c': '3'});
|
||||
var two = new Url('two', three, null, {'b': '2'});
|
||||
var one = new Url('one', two, null, {'a': '1'});
|
||||
|
||||
var match = rec.recognize(one);
|
||||
expect(match['allParams']).toEqual({'c': '3'});
|
||||
var match = rec.matchUrl(one);
|
||||
expect(match.allParams).toEqual({'c': '3'});
|
||||
});
|
||||
});
|
||||
|
||||
describe('wildcard segment', () => {
|
||||
it('should return a url path which matches the original url path', () => {
|
||||
var rec = new PathRecognizer('/wild/*everything');
|
||||
var rec = new ParamRoutePath('/wild/*everything');
|
||||
var url = parser.parse('/wild/super;variable=value/anotherPartAfterSlash');
|
||||
var match = rec.recognize(url);
|
||||
expect(match['urlPath']).toEqual('wild/super;variable=value/anotherPartAfterSlash');
|
||||
var match = rec.matchUrl(url);
|
||||
expect(match.urlPath).toEqual('wild/super;variable=value/anotherPartAfterSlash');
|
||||
});
|
||||
});
|
||||
});
|
|
@ -0,0 +1,51 @@
|
|||
import {
|
||||
AsyncTestCompleter,
|
||||
describe,
|
||||
it,
|
||||
iit,
|
||||
ddescribe,
|
||||
expect,
|
||||
inject,
|
||||
beforeEach,
|
||||
SpyObject
|
||||
} from 'angular2/testing_internal';
|
||||
|
||||
import {GeneratedUrl} from 'angular2/src/router/rules/route_paths/route_path';
|
||||
import {RegexRoutePath} from 'angular2/src/router/rules/route_paths/regex_route_path';
|
||||
import {parser, Url} from 'angular2/src/router/url_parser';
|
||||
|
||||
function emptySerializer(params) {
|
||||
return new GeneratedUrl('', {});
|
||||
}
|
||||
|
||||
export function main() {
|
||||
describe('RegexRoutePath', () => {
|
||||
|
||||
it('should throw when given an invalid regex',
|
||||
() => { expect(() => new RegexRoutePath('[abc', emptySerializer)).toThrowError(); });
|
||||
|
||||
it('should parse a single param using capture groups', () => {
|
||||
var rec = new RegexRoutePath('^(.+)$', emptySerializer);
|
||||
var url = parser.parse('hello');
|
||||
var match = rec.matchUrl(url);
|
||||
expect(match.allParams).toEqual({'0': 'hello', '1': 'hello'});
|
||||
});
|
||||
|
||||
it('should parse multiple params using capture groups', () => {
|
||||
var rec = new RegexRoutePath('^(.+)\\.(.+)$', emptySerializer);
|
||||
var url = parser.parse('hello.goodbye');
|
||||
var match = rec.matchUrl(url);
|
||||
expect(match.allParams).toEqual({'0': 'hello.goodbye', '1': 'hello', '2': 'goodbye'});
|
||||
});
|
||||
|
||||
it('should generate a url by calling the provided serializer', () => {
|
||||
function serializer(params) {
|
||||
return new GeneratedUrl(`/a/${params['a']}/b/${params['b']}`, {});
|
||||
}
|
||||
var rec = new RegexRoutePath('/a/(.+)/b/(.+)$', serializer);
|
||||
var params = {a: 'one', b: 'two'};
|
||||
var url = rec.generateUrl(params);
|
||||
expect(url.urlPath).toEqual('/a/one/b/two');
|
||||
});
|
||||
});
|
||||
}
|
|
@ -12,19 +12,20 @@ import {
|
|||
|
||||
import {Map, StringMapWrapper} from 'angular2/src/facade/collection';
|
||||
|
||||
import {RouteMatch, PathMatch, RedirectMatch} from 'angular2/src/router/route_recognizer';
|
||||
import {ComponentRecognizer} from 'angular2/src/router/component_recognizer';
|
||||
import {RouteMatch, PathMatch, RedirectMatch} from 'angular2/src/router/rules/rules';
|
||||
import {RuleSet} from 'angular2/src/router/rules/rule_set';
|
||||
import {GeneratedUrl} from 'angular2/src/router/rules/route_paths/route_path';
|
||||
|
||||
import {Route, Redirect} from 'angular2/src/router/route_config_decorator';
|
||||
import {Route, Redirect} from 'angular2/src/router/route_config/route_config_decorator';
|
||||
import {parser} from 'angular2/src/router/url_parser';
|
||||
import {PromiseWrapper} from 'angular2/src/facade/promise';
|
||||
|
||||
|
||||
export function main() {
|
||||
describe('ComponentRecognizer', () => {
|
||||
var recognizer: ComponentRecognizer;
|
||||
describe('RuleSet', () => {
|
||||
var recognizer: RuleSet;
|
||||
|
||||
beforeEach(() => { recognizer = new ComponentRecognizer(); });
|
||||
beforeEach(() => { recognizer = new RuleSet(); });
|
||||
|
||||
|
||||
it('should recognize a static segment', inject([AsyncTestCompleter], (async) => {
|
||||
|
@ -72,6 +73,21 @@ export function main() {
|
|||
});
|
||||
}));
|
||||
|
||||
it('should recognize a regex', inject([AsyncTestCompleter], (async) => {
|
||||
function emptySerializer(params): GeneratedUrl { return new GeneratedUrl('', {}); }
|
||||
|
||||
recognizer.config(
|
||||
new Route({regex: '^(.+)/(.+)$', serializer: emptySerializer, component: DummyCmpA}));
|
||||
recognize(recognizer, '/first/second')
|
||||
.then((solutions: RouteMatch[]) => {
|
||||
expect(solutions.length).toBe(1);
|
||||
expect(getComponentType(solutions[0])).toEqual(DummyCmpA);
|
||||
expect(getParams(solutions[0]))
|
||||
.toEqual({'0': 'first/second', '1': 'first', '2': 'second'});
|
||||
async.done();
|
||||
});
|
||||
}));
|
||||
|
||||
|
||||
it('should throw when given two routes that start with the same static segment', () => {
|
||||
recognizer.config(new Route({path: '/hello', component: DummyCmpA}));
|
||||
|
@ -123,6 +139,25 @@ export function main() {
|
|||
});
|
||||
|
||||
|
||||
it('should generate using a serializer', () => {
|
||||
function simpleSerializer(params): GeneratedUrl {
|
||||
var extra = {c: params['c']};
|
||||
return new GeneratedUrl(`/${params['a']}/${params['b']}`, extra);
|
||||
}
|
||||
|
||||
recognizer.config(new Route({
|
||||
name: 'Route1',
|
||||
regex: '^(.+)/(.+)$',
|
||||
serializer: simpleSerializer,
|
||||
component: DummyCmpA
|
||||
}));
|
||||
var params = {a: 'first', b: 'second', c: 'third'};
|
||||
var result = recognizer.generate('Route1', params);
|
||||
expect(result.urlPath).toEqual('/first/second');
|
||||
expect(result.urlParams).toEqual(['c=third']);
|
||||
});
|
||||
|
||||
|
||||
it('should throw in the absence of required params URLs', () => {
|
||||
recognizer.config(new Route({path: 'app/user/:name', component: DummyCmpA, name: 'User'}));
|
||||
expect(() => recognizer.generate('User', {}))
|
||||
|
@ -193,7 +228,7 @@ export function main() {
|
|||
});
|
||||
}
|
||||
|
||||
function recognize(recognizer: ComponentRecognizer, url: string): Promise<RouteMatch[]> {
|
||||
function recognize(recognizer: RuleSet, url: string): Promise<RouteMatch[]> {
|
||||
var parsedUrl = parser.parse(url);
|
||||
return PromiseWrapper.all(recognizer.recognize(parsedUrl));
|
||||
}
|
|
@ -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(); });
|
||||
|
||||
|
|
|
@ -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])
|
||||
|
|
|
@ -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
|
||||
|
|
Loading…
Reference in New Issue