chore(router): clang-format

This commit is contained in:
vsavkin 2016-05-04 15:01:27 -07:00
parent abfb522f83
commit b30ddfbfc5
8 changed files with 108 additions and 75 deletions

View File

@ -3,7 +3,8 @@ import {isBlank, isPresent, isString, isStringMap} from './facade/lang';
import {BaseException} from './facade/exceptions'; import {BaseException} from './facade/exceptions';
import {ListWrapper, StringMapWrapper} from './facade/collection'; import {ListWrapper, StringMapWrapper} from './facade/collection';
export function link(segment: RouteSegment, routeTree: RouteTree, urlTree: UrlTree, commands: any[]): UrlTree { export function link(segment: RouteSegment, routeTree: RouteTree, urlTree: UrlTree,
commands: any[]): UrlTree {
if (commands.length === 0) return urlTree; if (commands.length === 0) return urlTree;
let normalizedCommands = _normalizeCommands(commands); let normalizedCommands = _normalizeCommands(commands);
@ -12,20 +13,22 @@ export function link(segment: RouteSegment, routeTree: RouteTree, urlTree: UrlTr
} }
let startingNode = _findStartingNode(normalizedCommands, urlTree, segment, routeTree); let startingNode = _findStartingNode(normalizedCommands, urlTree, segment, routeTree);
let updated = normalizedCommands.commands.length > 0 ? let updated =
_updateMany(ListWrapper.clone(startingNode.children), normalizedCommands.commands) : []; normalizedCommands.commands.length > 0 ?
_updateMany(ListWrapper.clone(startingNode.children), normalizedCommands.commands) :
[];
let newRoot = _constructNewTree(rootNode(urlTree), startingNode, updated); let newRoot = _constructNewTree(rootNode(urlTree), startingNode, updated);
return new UrlTree(newRoot); return new UrlTree(newRoot);
} }
function _navigateToRoot(normalizedChange:_NormalizedNavigationCommands):boolean { function _navigateToRoot(normalizedChange: _NormalizedNavigationCommands): boolean {
return normalizedChange.isAbsolute && normalizedChange.commands.length === 1 && normalizedChange.commands[0] == "/"; return normalizedChange.isAbsolute && normalizedChange.commands.length === 1 &&
normalizedChange.commands[0] == "/";
} }
class _NormalizedNavigationCommands { class _NormalizedNavigationCommands {
constructor(public isAbsolute: boolean, constructor(public isAbsolute: boolean, public numberOfDoubleDots: number,
public numberOfDoubleDots: number,
public commands: any[]) {} public commands: any[]) {}
} }
@ -52,18 +55,18 @@ function _normalizeCommands(commands: any[]): _NormalizedNavigationCommands {
// first exp is treated in a special way // first exp is treated in a special way
if (i == 0) { if (i == 0) {
if (j == 0 && cc == ".") { // './a' if (j == 0 && cc == ".") { // './a'
// skip it // skip it
} else if (j == 0 && cc == "") { // '/a' } else if (j == 0 && cc == "") { // '/a'
isAbsolute = true; isAbsolute = true;
} else if (cc == "..") { // '../a' } else if (cc == "..") { // '../a'
numberOfDoubleDots++; numberOfDoubleDots++;
} else if (cc != '') { } else if (cc != '') {
res.push(cc); res.push(cc);
} }
} else { } else {
if (cc != ''){ if (cc != '') {
res.push(cc); res.push(cc);
} }
} }
@ -73,7 +76,8 @@ function _normalizeCommands(commands: any[]): _NormalizedNavigationCommands {
return new _NormalizedNavigationCommands(isAbsolute, numberOfDoubleDots, res); return new _NormalizedNavigationCommands(isAbsolute, numberOfDoubleDots, res);
} }
function _findUrlSegment(segment: RouteSegment, routeTree: RouteTree, urlTree: UrlTree, numberOfDoubleDots: number): UrlSegment { function _findUrlSegment(segment: RouteSegment, routeTree: RouteTree, urlTree: UrlTree,
numberOfDoubleDots: number): UrlSegment {
let s = segment; let s = segment;
while (s.urlSegments.length === 0) { while (s.urlSegments.length === 0) {
s = routeTree.parent(s); s = routeTree.parent(s);
@ -86,11 +90,13 @@ function _findUrlSegment(segment: RouteSegment, routeTree: RouteTree, urlTree: U
return path[path.length - 1 - numberOfDoubleDots]; return path[path.length - 1 - numberOfDoubleDots];
} }
function _findStartingNode(normalizedChange:_NormalizedNavigationCommands, urlTree:UrlTree, segment:RouteSegment, routeTree:RouteTree):TreeNode<UrlSegment> { function _findStartingNode(normalizedChange: _NormalizedNavigationCommands, urlTree: UrlTree,
segment: RouteSegment, routeTree: RouteTree): TreeNode<UrlSegment> {
if (normalizedChange.isAbsolute) { if (normalizedChange.isAbsolute) {
return rootNode(urlTree); return rootNode(urlTree);
} else { } else {
let urlSegment = _findUrlSegment(segment, routeTree, urlTree, normalizedChange.numberOfDoubleDots); let urlSegment =
_findUrlSegment(segment, routeTree, urlTree, normalizedChange.numberOfDoubleDots);
return _findMatchingNode(urlSegment, rootNode(urlTree)); return _findMatchingNode(urlSegment, rootNode(urlTree));
} }
} }
@ -110,7 +116,7 @@ function _constructNewTree(node: TreeNode<UrlSegment>, original: TreeNode<UrlSeg
return new TreeNode<UrlSegment>(node.value, updated); return new TreeNode<UrlSegment>(node.value, updated);
} else { } else {
return new TreeNode<UrlSegment>( return new TreeNode<UrlSegment>(
node.value, node.children.map(c => _constructNewTree(c, original, updated))); node.value, node.children.map(c => _constructNewTree(c, original, updated)));
} }
} }
@ -140,7 +146,7 @@ function _update(node: TreeNode<UrlSegment>, commands: any[]): TreeNode<UrlSegme
return _recurse(newSegment, node, rest); return _recurse(newSegment, node, rest);
// next one is a params command && can reuse the node // next one is a params command && can reuse the node
} else if (isStringMap(next) && _compare(segment, _stringify(next), node.value)){ } else if (isStringMap(next) && _compare(segment, _stringify(next), node.value)) {
return _recurse(node.value, node, rest.slice(1)); return _recurse(node.value, node, rest.slice(1));
// next one is a params command && cannot reuse the node // next one is a params command && cannot reuse the node
@ -159,7 +165,7 @@ function _update(node: TreeNode<UrlSegment>, commands: any[]): TreeNode<UrlSegme
} }
} }
function _stringify(params: {[key: string]: any}):{[key: string]: string} { function _stringify(params: {[key: string]: any}): {[key: string]: string} {
let res = {}; let res = {};
StringMapWrapper.forEach(params, (v, k) => res[k] = v.toString()); StringMapWrapper.forEach(params, (v, k) => res[k] = v.toString());
return res; return res;
@ -169,7 +175,8 @@ function _compare(path: string, params: {[key: string]: any}, segment: UrlSegmen
return path == segment.segment && StringMapWrapper.equals(params, segment.parameters); return path == segment.segment && StringMapWrapper.equals(params, segment.parameters);
} }
function _recurse(urlSegment: UrlSegment, node: TreeNode<UrlSegment>, rest: any[]): TreeNode<UrlSegment> { function _recurse(urlSegment: UrlSegment, node: TreeNode<UrlSegment>,
rest: any[]): TreeNode<UrlSegment> {
if (rest.length === 0) { if (rest.length === 0) {
return new TreeNode<UrlSegment>(urlSegment, []); return new TreeNode<UrlSegment>(urlSegment, []);
} }

View File

@ -22,7 +22,7 @@ import {stringify} from "../facade/lang";
*/ */
export abstract class RouteMetadata { export abstract class RouteMetadata {
abstract get path(): string; abstract get path(): string;
abstract get component(): Type|string; abstract get component(): Type | string;
} }
/** /**
@ -31,8 +31,8 @@ export abstract class RouteMetadata {
*/ */
export class Route implements RouteMetadata { export class Route implements RouteMetadata {
path: string; path: string;
component: Type|string; component: Type | string;
constructor({path, component}: {path?: string, component?: Type|string} = {}) { constructor({path, component}: {path?: string, component?: Type | string} = {}) {
this.path = path; this.path = path;
this.component = component; this.component = component;
} }

View File

@ -1,4 +1,13 @@
import {RouteSegment, UrlSegment, Tree, TreeNode, rootNode, UrlTree, RouteTree, equalUrlSegments} from './segments'; import {
RouteSegment,
UrlSegment,
Tree,
TreeNode,
rootNode,
UrlTree,
RouteTree,
equalUrlSegments
} from './segments';
import {RoutesMetadata, RouteMetadata} from './metadata/metadata'; import {RoutesMetadata, RouteMetadata} from './metadata/metadata';
import {Type, isBlank, isPresent, stringify} from './facade/lang'; import {Type, isBlank, isPresent, stringify} from './facade/lang';
import {ListWrapper, StringMapWrapper} from './facade/collection'; import {ListWrapper, StringMapWrapper} from './facade/collection';
@ -8,14 +17,16 @@ import {ComponentResolver} from '@angular/core';
import {DEFAULT_OUTLET_NAME} from './constants'; import {DEFAULT_OUTLET_NAME} from './constants';
import {reflector} from '@angular/core'; import {reflector} from '@angular/core';
export function recognize(componentResolver: ComponentResolver, rootComponent: Type, export function recognize(componentResolver: ComponentResolver, rootComponent: Type, url: UrlTree,
url: UrlTree, existingTree: RouteTree): Promise<RouteTree> { existingTree: RouteTree): Promise<RouteTree> {
let matched = new _MatchResult(rootComponent, [url.root], {}, rootNode(url).children, []); let matched = new _MatchResult(rootComponent, [url.root], {}, rootNode(url).children, []);
return _constructSegment(componentResolver, matched, rootNode(existingTree)).then(roots => new RouteTree(roots[0])); return _constructSegment(componentResolver, matched, rootNode(existingTree))
.then(roots => new RouteTree(roots[0]));
} }
function _recognize(componentResolver: ComponentResolver, parentComponent: Type, function _recognize(componentResolver: ComponentResolver, parentComponent: Type,
url: TreeNode<UrlSegment>, existingSegments: TreeNode<RouteSegment>[]): Promise<TreeNode<RouteSegment>[]> { url: TreeNode<UrlSegment>,
existingSegments: TreeNode<RouteSegment>[]): Promise<TreeNode<RouteSegment>[]> {
let metadata = _readMetadata(parentComponent); // should read from the factory instead let metadata = _readMetadata(parentComponent); // should read from the factory instead
if (isBlank(metadata)) { if (isBlank(metadata)) {
throw new BaseException( throw new BaseException(
@ -30,29 +41,34 @@ function _recognize(componentResolver: ComponentResolver, parentComponent: Type,
} }
let segmentsWithRightOutlet = existingSegments.filter(r => r.value.outlet == match.outlet); let segmentsWithRightOutlet = existingSegments.filter(r => r.value.outlet == match.outlet);
let segmentWithRightOutlet = segmentsWithRightOutlet.length > 0 ? segmentsWithRightOutlet[0] : null; let segmentWithRightOutlet =
segmentsWithRightOutlet.length > 0 ? segmentsWithRightOutlet[0] : null;
let main = _constructSegment(componentResolver, match, segmentWithRightOutlet); let main = _constructSegment(componentResolver, match, segmentWithRightOutlet);
let aux = let aux = _recognizeMany(componentResolver, parentComponent, match.aux, existingSegments)
_recognizeMany(componentResolver, parentComponent, match.aux, existingSegments).then(_checkOutletNameUniqueness); .then(_checkOutletNameUniqueness);
return PromiseWrapper.all([main, aux]).then(ListWrapper.flatten); return PromiseWrapper.all([main, aux]).then(ListWrapper.flatten);
} }
function _recognizeMany(componentResolver: ComponentResolver, parentComponent: Type, function _recognizeMany(
urls: TreeNode<UrlSegment>[], existingSegments: TreeNode<RouteSegment>[]): Promise<TreeNode<RouteSegment>[]> { componentResolver: ComponentResolver, parentComponent: Type, urls: TreeNode<UrlSegment>[],
let recognized = urls.map(u => _recognize(componentResolver, parentComponent, u, existingSegments)); existingSegments: TreeNode<RouteSegment>[]): Promise<TreeNode<RouteSegment>[]> {
let recognized =
urls.map(u => _recognize(componentResolver, parentComponent, u, existingSegments));
return PromiseWrapper.all(recognized).then(ListWrapper.flatten); return PromiseWrapper.all(recognized).then(ListWrapper.flatten);
} }
function _constructSegment(componentResolver: ComponentResolver, function _constructSegment(
matched: _MatchResult, existingSegment: TreeNode<RouteSegment>): Promise<TreeNode<RouteSegment>[]> { componentResolver: ComponentResolver, matched: _MatchResult,
existingSegment: TreeNode<RouteSegment>): Promise<TreeNode<RouteSegment>[]> {
return componentResolver.resolveComponent(matched.component) return componentResolver.resolveComponent(matched.component)
.then(factory => { .then(factory => {
let segment = _createOrReuseSegment(matched, factory, existingSegment); let segment = _createOrReuseSegment(matched, factory, existingSegment);
let existingChildren = isPresent(existingSegment) ? existingSegment.children : []; let existingChildren = isPresent(existingSegment) ? existingSegment.children : [];
if (matched.leftOverUrl.length > 0) { if (matched.leftOverUrl.length > 0) {
return _recognizeMany(componentResolver, factory.componentType, matched.leftOverUrl, existingChildren) return _recognizeMany(componentResolver, factory.componentType, matched.leftOverUrl,
existingChildren)
.then(children => [new TreeNode<RouteSegment>(segment, children)]); .then(children => [new TreeNode<RouteSegment>(segment, children)]);
} else { } else {
return _recognizeLeftOvers(componentResolver, factory.componentType, existingChildren) return _recognizeLeftOvers(componentResolver, factory.componentType, existingChildren)
@ -61,21 +77,23 @@ function _constructSegment(componentResolver: ComponentResolver,
}); });
} }
function _createOrReuseSegment(matched: _MatchResult, factory: ComponentFactory<any>, segmentNode: TreeNode<RouteSegment>): RouteSegment { function _createOrReuseSegment(matched: _MatchResult, factory: ComponentFactory<any>,
segmentNode: TreeNode<RouteSegment>): RouteSegment {
let segment = isPresent(segmentNode) ? segmentNode.value : null; let segment = isPresent(segmentNode) ? segmentNode.value : null;
if (isPresent(segment) && equalUrlSegments(segment.urlSegments, matched.consumedUrlSegments) if (isPresent(segment) && equalUrlSegments(segment.urlSegments, matched.consumedUrlSegments) &&
&& StringMapWrapper.equals(segment.parameters, matched.parameters) && StringMapWrapper.equals(segment.parameters, matched.parameters) &&
segment.outlet == matched.outlet && factory.componentType == segment.type) { segment.outlet == matched.outlet && factory.componentType == segment.type) {
return segment; return segment;
} else { } else {
return new RouteSegment(matched.consumedUrlSegments, matched.parameters, matched.outlet, return new RouteSegment(matched.consumedUrlSegments, matched.parameters, matched.outlet,
factory.componentType, factory); factory.componentType, factory);
} }
} }
function _recognizeLeftOvers(componentResolver: ComponentResolver, function _recognizeLeftOvers(
parentComponent: Type, existingSegments: TreeNode<RouteSegment>[]): Promise<TreeNode<RouteSegment>[]> { componentResolver: ComponentResolver, parentComponent: Type,
existingSegments: TreeNode<RouteSegment>[]): Promise<TreeNode<RouteSegment>[]> {
return componentResolver.resolveComponent(parentComponent) return componentResolver.resolveComponent(parentComponent)
.then(factory => { .then(factory => {
let metadata = _readMetadata(factory.componentType); let metadata = _readMetadata(factory.componentType);
@ -87,14 +105,20 @@ function _recognizeLeftOvers(componentResolver: ComponentResolver,
if (r.length === 0) { if (r.length === 0) {
return PromiseWrapper.resolve([]); return PromiseWrapper.resolve([]);
} else { } else {
let segmentsWithMatchingOutlet = existingSegments.filter(r => r.value.outlet == DEFAULT_OUTLET_NAME); let segmentsWithMatchingOutlet =
let segmentWithMatchingOutlet = segmentsWithMatchingOutlet.length > 0 ? segmentsWithMatchingOutlet[0] : null; existingSegments.filter(r => r.value.outlet == DEFAULT_OUTLET_NAME);
let existingChildren = isPresent(segmentWithMatchingOutlet) ? segmentWithMatchingOutlet.children : []; let segmentWithMatchingOutlet =
segmentsWithMatchingOutlet.length > 0 ? segmentsWithMatchingOutlet[0] : null;
let existingChildren =
isPresent(segmentWithMatchingOutlet) ? segmentWithMatchingOutlet.children : [];
return _recognizeLeftOvers(componentResolver, r[0].component, existingChildren).then(children => { return _recognizeLeftOvers(componentResolver, r[0].component, existingChildren)
.then(children => {
return componentResolver.resolveComponent(r[0].component) return componentResolver.resolveComponent(r[0].component)
.then(factory => { .then(factory => {
let segment = _createOrReuseSegment(new _MatchResult(r[0].component, [], {}, [], []), factory, segmentWithMatchingOutlet); let segment =
_createOrReuseSegment(new _MatchResult(r[0].component, [], {}, [], []),
factory, segmentWithMatchingOutlet);
return [new TreeNode<RouteSegment>(segment, children)]; return [new TreeNode<RouteSegment>(segment, children)];
}); });
}); });
@ -177,15 +201,14 @@ function _checkOutletNameUniqueness(nodes: TreeNode<RouteSegment>[]): TreeNode<R
} }
class _MatchResult { class _MatchResult {
constructor(public component: Type|string, public consumedUrlSegments: UrlSegment[], constructor(public component: Type | string, public consumedUrlSegments: UrlSegment[],
public parameters: {[key: string]: string}, public parameters: {[key: string]: string},
public leftOverUrl: TreeNode<UrlSegment>[], public aux: TreeNode<UrlSegment>[]) {} public leftOverUrl: TreeNode<UrlSegment>[], public aux: TreeNode<UrlSegment>[]) {}
get outlet():string { get outlet(): string {
return this.consumedUrlSegments.length === 0 || return this.consumedUrlSegments.length === 0 || isBlank(this.consumedUrlSegments[0].outlet) ?
isBlank(this.consumedUrlSegments[0].outlet) ? DEFAULT_OUTLET_NAME :
DEFAULT_OUTLET_NAME : this.consumedUrlSegments[0].outlet;
this.consumedUrlSegments[0].outlet;
} }
} }

View File

@ -20,7 +20,7 @@ import {
TreeNode, TreeNode,
UrlSegment, UrlSegment,
serializeRouteSegmentTree, serializeRouteSegmentTree,
createEmptyRouteTree createEmptyRouteTree
} from './segments'; } from './segments';
import {hasLifecycleHook} from './lifecycle_reflector'; import {hasLifecycleHook} from './lifecycle_reflector';
import {DEFAULT_OUTLET_NAME} from './constants'; import {DEFAULT_OUTLET_NAME} from './constants';
@ -240,7 +240,7 @@ class _ActivateSegments {
if (curr === prev) { if (curr === prev) {
this.activateChildSegments(currNode, prevNode, outlet.outletMap, this.activateChildSegments(currNode, prevNode, outlet.outletMap,
components.concat([outlet.component])); components.concat([outlet.component]));
} else { } else {
this.deactivateOutlet(outlet, components); this.deactivateOutlet(outlet, components);
if (this.performMutation) { if (this.performMutation) {

View File

@ -122,7 +122,7 @@ export class RouteSegment {
get stringifiedUrlSegments(): string { return this.urlSegments.map(s => s.toString()).join("/"); } get stringifiedUrlSegments(): string { return this.urlSegments.map(s => s.toString()).join("/"); }
} }
export function createEmptyRouteTree(type:Type): RouteTree { export function createEmptyRouteTree(type: Type): RouteTree {
let root = new RouteSegment([new UrlSegment("", {}, null)], {}, DEFAULT_OUTLET_NAME, type, null); let root = new RouteSegment([new UrlSegment("", {}, null)], {}, DEFAULT_OUTLET_NAME, type, null);
return new RouteTree(new TreeNode<RouteSegment>(root, [])); return new RouteTree(new TreeNode<RouteSegment>(root, []));
} }

View File

@ -96,7 +96,8 @@ export function main() {
.toHaveText('team 22 { hello victor, aux: simple }'); .toHaveText('team 22 { hello victor, aux: simple }');
}))); })));
it('should deactivate outlets', fakeAsync(inject([Router, TestComponentBuilder], (router, tcb) => { it('should deactivate outlets',
fakeAsync(inject([Router, TestComponentBuilder], (router, tcb) => {
let fixture = tcb.createFakeAsync(RootCmp); let fixture = tcb.createFakeAsync(RootCmp);
router.navigateByUrl('/team/22/user/victor(/simple)'); router.navigateByUrl('/team/22/user/victor(/simple)');
@ -227,11 +228,11 @@ export function main() {
}))); })));
it("should support top-level link", it("should support top-level link",
fakeAsync(inject([Router, TestComponentBuilder], (router, tcb) => { fakeAsync(inject([Router, TestComponentBuilder], (router, tcb) => {
let fixture = tcb.createFakeAsync(LinkCmp); let fixture = tcb.createFakeAsync(LinkCmp);
advance(fixture); advance(fixture);
expect(fixture.debugElement.nativeElement).toHaveText('link'); expect(fixture.debugElement.nativeElement).toHaveText('link');
}))); })));
} }
}); });
} }

View File

@ -183,9 +183,9 @@ export function main() {
let p = parser.parse("/a(ap)/c(cp)"); let p = parser.parse("/a(ap)/c(cp)");
let c = p.firstChild(p.root); let c = p.firstChild(p.root);
let child = new RouteSegment([], {'one':'1'}, null, null, null); let child = new RouteSegment([], {'one': '1'}, null, null, null);
let root = new TreeNode<RouteSegment>(new RouteSegment([c], {}, null, null, null), let root = new TreeNode<RouteSegment>(new RouteSegment([c], {}, null, null, null),
[new TreeNode<RouteSegment>(child, [])]); [new TreeNode<RouteSegment>(child, [])]);
let tree = new RouteTree(root); let tree = new RouteTree(root);
let t = link(child, tree, p, ["./c2"]); let t = link(child, tree, p, ["./c2"]);

View File

@ -22,7 +22,7 @@ import {DEFAULT_OUTLET_NAME} from '../src/constants';
export function main() { export function main() {
describe('recognize', () => { describe('recognize', () => {
let emptyRouteTree = createEmptyRouteTree(ComponentA); let emptyRouteTree = createEmptyRouteTree(ComponentA);
it('should handle position args', it('should handle position args',
inject([AsyncTestCompleter, ComponentResolver], (async, resolver) => { inject([AsyncTestCompleter, ComponentResolver], (async, resolver) => {
recognize(resolver, ComponentA, tree("b/paramB/c/paramC/d"), emptyRouteTree) recognize(resolver, ComponentA, tree("b/paramB/c/paramC/d"), emptyRouteTree)
@ -191,17 +191,19 @@ export function main() {
it("should reuse existing segments", it("should reuse existing segments",
inject([AsyncTestCompleter, ComponentResolver], (async, resolver) => { inject([AsyncTestCompleter, ComponentResolver], (async, resolver) => {
recognize(resolver, ComponentA, tree("/b/1/d"), emptyRouteTree).then(t1 => { recognize(resolver, ComponentA, tree("/b/1/d"), emptyRouteTree)
recognize(resolver, ComponentA, tree("/b/1/e"), t1).then(t2 => { .then(t1 => {
expect(t1.root).toBe(t2.root); recognize(resolver, ComponentA, tree("/b/1/e"), t1)
expect(t1.firstChild(t1.root)).toBe(t2.firstChild(t2.root)); .then(t2 => {
expect(t1.firstChild(t1.firstChild(t1.root))).not.toBe( expect(t1.root).toBe(t2.root);
t2.firstChild(t2.firstChild(t2.root))); expect(t1.firstChild(t1.root)).toBe(t2.firstChild(t2.root));
expect(t1.firstChild(t1.firstChild(t1.root)))
.not.toBe(t2.firstChild(t2.firstChild(t2.root)));
async.done(); async.done();
}); });
}); });
})); }));
}); });
} }