X Tutup
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions modules/angular2/alt_router.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
/**
* @module
* @description
* Alternative implementation of the router. Experimental.
*/

export {Router, RouterOutletMap} from './src/alt_router/router';
export {RouteSegment} from './src/alt_router/segments';
export {Routes} from './src/alt_router/metadata/decorators';
export {Route} from './src/alt_router/metadata/metadata';
export {RouterUrlParser, DefaultRouterUrlParser} from './src/alt_router/router_url_parser';
export {OnActivate} from './src/alt_router/interfaces';

import {RouterOutlet} from './src/alt_router/directives/router_outlet';
import {CONST_EXPR} from './src/facade/lang';

export const ROUTER_DIRECTIVES: any[] = CONST_EXPR([RouterOutlet]);
34 changes: 34 additions & 0 deletions modules/angular2/src/alt_router/directives/router_outlet.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import {
ResolvedReflectiveProvider,
Directive,
DynamicComponentLoader,
ViewContainerRef,
Input,
ComponentRef,
ComponentFactory,
ReflectiveInjector
} from 'angular2/core';
import {RouterOutletMap} from '../router';
import {isPresent} from 'angular2/src/facade/lang';

@Directive({selector: 'router-outlet'})
export class RouterOutlet {
private _loaded: ComponentRef;
public outletMap: RouterOutletMap;
@Input() name: string = "";

constructor(parentOutletMap: RouterOutletMap, private _location: ViewContainerRef) {
parentOutletMap.registerOutlet("", this);
}

load(factory: ComponentFactory, providers: ResolvedReflectiveProvider[],
outletMap: RouterOutletMap): ComponentRef {
if (isPresent(this._loaded)) {
this._loaded.destroy();
}
this.outletMap = outletMap;
let inj = ReflectiveInjector.fromResolvedProviders(providers, this._location.parentInjector);
this._loaded = this._location.createComponent(factory, this._location.length, inj, []);
return this._loaded;
}
}
6 changes: 6 additions & 0 deletions modules/angular2/src/alt_router/interfaces.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import {RouteSegment, Tree} from './segments';

export interface OnActivate {
routerOnActivate(curr: RouteSegment, prev?: RouteSegment, currTree?: Tree<RouteSegment>,
prevTree?: Tree<RouteSegment>): void;
}
5 changes: 5 additions & 0 deletions modules/angular2/src/alt_router/lifecycle_reflector.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import './interfaces.dart';
bool hasLifecycleHook(String name, Object obj) {
if (name == "routerOnActivate") return obj is OnActivate;
return false;
}
7 changes: 7 additions & 0 deletions modules/angular2/src/alt_router/lifecycle_reflector.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import {Type} from 'angular2/src/facade/lang';

export function hasLifecycleHook(name: string, obj: Object): boolean {
let type = obj.constructor;
if (!(type instanceof Type)) return false;
return name in(<any>type).prototype;
}
8 changes: 8 additions & 0 deletions modules/angular2/src/alt_router/metadata/decorators.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
library angular.alt_router.decorators;

import 'metadata.dart';
export 'metadata.dart';

class Routes extends RoutesMetadata {
const Routes(List<RouteMetadata> routes): super(routes);
}
7 changes: 7 additions & 0 deletions modules/angular2/src/alt_router/metadata/decorators.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import {RoutesMetadata, RouteMetadata} from "./metadata";
import {makeDecorator} from 'angular2/src/core/util/decorators';
export interface RoutesFactory {
(routes: RouteMetadata[]): any;
new (routes: RouteMetadata[]): RoutesMetadata;
}
export var Routes: RoutesFactory = <RoutesFactory>makeDecorator(RoutesMetadata);
23 changes: 23 additions & 0 deletions modules/angular2/src/alt_router/metadata/metadata.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import {CONST, Type, stringify} from "angular2/src/facade/lang";

export abstract class RouteMetadata {
abstract get path(): string;
abstract get component(): Type;
}

@CONST()
export class Route implements RouteMetadata {
path: string;
component: Type;
constructor({path, component}: {path?: string, component?: Type} = {}) {
this.path = path;
this.component = component;
}
toString(): string { return `@Route(${this.path}, ${stringify(this.component)})`; }
}

@CONST()
export class RoutesMetadata {
constructor(public routes: RouteMetadata[]) {}
toString(): string { return `@Routes(${this.routes})`; }
}
84 changes: 84 additions & 0 deletions modules/angular2/src/alt_router/recognize.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
import {RouteSegment, UrlSegment, Tree} from './segments';
import {RoutesMetadata, RouteMetadata} from './metadata/metadata';
import {Type, isPresent, stringify} from 'angular2/src/facade/lang';
import {PromiseWrapper} from 'angular2/src/facade/promise';
import {BaseException} from 'angular2/src/facade/exceptions';
import {ComponentResolver} from 'angular2/core';
import {reflector} from 'angular2/src/core/reflection/reflection';

export function recognize(componentResolver: ComponentResolver, type: Type,
url: Tree<UrlSegment>): Promise<Tree<RouteSegment>> {
return _recognize(componentResolver, type, url, url.root)
.then(nodes => new Tree<RouteSegment>(nodes));
}

function _recognize(componentResolver: ComponentResolver, type: Type, url: Tree<UrlSegment>,
current: UrlSegment): Promise<RouteSegment[]> {
let metadata = _readMetadata(type); // should read from the factory instead

let matched;
try {
matched = _match(metadata, url, current);
} catch (e) {
return PromiseWrapper.reject(e, null);
}

return componentResolver.resolveComponent(matched.route.component)
.then(factory => {
let segment = new RouteSegment(matched.consumedUrlSegments, matched.parameters, "",
matched.route.component, factory);

if (isPresent(matched.leftOver)) {
return _recognize(componentResolver, matched.route.component, url, matched.leftOver)
.then(children => [segment].concat(children));
} else {
return [segment];
}
});
}

function _match(metadata: RoutesMetadata, url: Tree<UrlSegment>,
current: UrlSegment): _MatchingResult {
for (let r of metadata.routes) {
let matchingResult = _matchWithParts(r, url, current);
if (isPresent(matchingResult)) {
return matchingResult;
}
}
throw new BaseException("Cannot match any routes");
}

function _matchWithParts(route: RouteMetadata, url: Tree<UrlSegment>,
current: UrlSegment): _MatchingResult {
let parts = route.path.split("/");
let parameters = {};
let consumedUrlSegments = [];

let u = current;
for (let i = 0; i < parts.length; ++i) {
consumedUrlSegments.push(u);
let p = parts[i];
if (p.startsWith(":")) {
let segment = u.segment;
parameters[p.substring(1)] = segment;
} else if (p != u.segment) {
return null;
}
u = url.firstChild(u);
}
return new _MatchingResult(route, consumedUrlSegments, parameters, u);
}

class _MatchingResult {
constructor(public route: RouteMetadata, public consumedUrlSegments: UrlSegment[],
public parameters: {[key: string]: string}, public leftOver: UrlSegment) {}
}

function _readMetadata(componentType: Type) {
let metadata = reflector.annotations(componentType).filter(f => f instanceof RoutesMetadata);
if (metadata.length === 0) {
throw new BaseException(
`Component '${stringify(componentType)}' does not have route configuration`);
}
return metadata[0];
}
55 changes: 55 additions & 0 deletions modules/angular2/src/alt_router/router.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import {provide, ReflectiveInjector, ComponentResolver} from 'angular2/core';
import {RouterOutlet} from './directives/router_outlet';
import {Type, isBlank, isPresent} from 'angular2/src/facade/lang';
import {RouterUrlParser} from './router_url_parser';
import {recognize} from './recognize';
import {equalSegments, routeSegmentComponentFactory, RouteSegment, Tree} from './segments';
import {hasLifecycleHook} from './lifecycle_reflector';

export class RouterOutletMap {
/** @internal */
_outlets: {[name: string]: RouterOutlet} = {};
registerOutlet(name: string, outlet: RouterOutlet): void { this._outlets[name] = outlet; }
}

export class Router {
private prevTree: Tree<RouteSegment>;
constructor(private _componentType: Type, private _componentResolver: ComponentResolver,
private _urlParser: RouterUrlParser, private _routerOutletMap: RouterOutletMap) {}

navigateByUrl(url: string): Promise<void> {
let urlSegmentTree = this._urlParser.parse(url.substring(1));
return recognize(this._componentResolver, this._componentType, urlSegmentTree)
.then(currTree => {
let prevRoot = isPresent(this.prevTree) ? this.prevTree.root : null;
_loadSegments(currTree, currTree.root, this.prevTree, prevRoot, this,
this._routerOutletMap);
this.prevTree = currTree;
});
}
}

function _loadSegments(currTree: Tree<RouteSegment>, curr: RouteSegment,
prevTree: Tree<RouteSegment>, prev: RouteSegment, router: Router,
parentOutletMap: RouterOutletMap): void {
let outlet = parentOutletMap._outlets[curr.outlet];

let outletMap;
if (equalSegments(curr, prev)) {
outletMap = outlet.outletMap;
} else {
outletMap = new RouterOutletMap();
let resolved = ReflectiveInjector.resolve(
[provide(RouterOutletMap, {useValue: outletMap}), provide(RouteSegment, {useValue: curr})]);
let ref = outlet.load(routeSegmentComponentFactory(curr), resolved, outletMap);
if (hasLifecycleHook("routerOnActivate", ref.instance)) {
ref.instance.routerOnActivate(curr, prev, currTree, prevTree);
}
}

if (isPresent(currTree.firstChild(curr))) {
let cc = currTree.firstChild(curr);
let pc = isBlank(prevTree) ? null : prevTree.firstChild(prev);
_loadSegments(currTree, cc, prevTree, pc, router, outletMap);
}
}
27 changes: 27 additions & 0 deletions modules/angular2/src/alt_router/router_url_parser.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import {UrlSegment, Tree} from './segments';
import {BaseException} from 'angular2/src/facade/exceptions';

export abstract class RouterUrlParser { abstract parse(url: string): Tree<UrlSegment>; }

export class DefaultRouterUrlParser extends RouterUrlParser {
parse(url: string): Tree<UrlSegment> {
if (url.length === 0) {
throw new BaseException(`Invalid url '${url}'`);
}
return new Tree<UrlSegment>(this._parseNodes(url));
}

private _parseNodes(url: string): UrlSegment[] {
Copy link
Copy Markdown
Member

@gkalpak gkalpak Apr 23, 2016

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Isn't this method essentially doing url.split('/').map(segment => new UrlSegment(segment, {}, '')) ?

let index = url.indexOf("/", 1);
let children: UrlSegment[];
let currentUrl;
if (index > -1) {
children = this._parseNodes(url.substring(index + 1));
currentUrl = url.substring(0, index);
} else {
children = [];
currentUrl = url;
}
return [new UrlSegment(currentUrl, {}, "")].concat(children);
}
}
66 changes: 66 additions & 0 deletions modules/angular2/src/alt_router/segments.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import {ComponentFactory} from 'angular2/core';
import {StringMapWrapper, ListWrapper} from 'angular2/src/facade/collection';
import {Type, isBlank} from 'angular2/src/facade/lang';

export class Tree<T> {
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

OOC, why is this called Tree. Are there any plans to allow multiple children in the future ?

constructor(private _nodes: T[]) {}

get root(): T { return this._nodes[0]; }

parent(t: T): T {
let index = this._nodes.indexOf(t);
return index > 0 ? this._nodes[index - 1] : null;
}

children(t: T): T[] {
let index = this._nodes.indexOf(t);
return index > -1 && index < this._nodes.length - 1 ? [this._nodes[index + 1]] : [];
}

firstChild(t: T): T {
let index = this._nodes.indexOf(t);
return index > -1 && index < this._nodes.length - 1 ? this._nodes[index + 1] : null;
}

pathToRoot(t: T): T[] {
Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

rename into pathFromRoot

let index = this._nodes.indexOf(t);
return index > -1 ? this._nodes.slice(0, index + 1) : null;
}
}

export class UrlSegment {
constructor(public segment: string, public parameters: {[key: string]: string},
public outlet: string) {}
}

export class RouteSegment {
/** @internal */
_type: Type;

/** @internal */
_componentFactory: ComponentFactory;

/** @internal */
_parameters: {[key: string]: string};

constructor(public urlSegments: UrlSegment[], parameters: {[key: string]: string},
public outlet: string, type: Type, componentFactory: ComponentFactory) {
this._type = type;
this._componentFactory = componentFactory;
this._parameters = parameters;
}

getParam(param: string): string { return this._parameters[param]; }

get type(): Type { return this._type; }
}

export function equalSegments(a: RouteSegment, b: RouteSegment): boolean {
if (isBlank(a) && !isBlank(b)) return false;
if (!isBlank(a) && isBlank(b)) return false;
return a._type === b._type && StringMapWrapper.equals(a._parameters, b._parameters);
}

export function routeSegmentComponentFactory(a: RouteSegment): ComponentFactory {
return a._componentFactory;
}
Loading
X Tutup