feat(router): implement relative navigation

This commit is contained in:
vsavkin 2016-05-26 16:51:56 -07:00
parent 86f47273bc
commit c179b5033b
5 changed files with 226 additions and 64 deletions

View File

@ -5,6 +5,7 @@ import {
Input
} from '@angular/core';
import {Router} from '../router';
import {ActivatedRoute} from '../router_state';
/**
* The RouterLink directive lets you link to specific parts of your app.
@ -12,7 +13,7 @@ import {Router} from '../router';
* Consider the following route configuration:
* ```
* [{ name: 'user', path: '/user', component: UserCmp }]
* [{ path: '/user', component: UserCmp }]
* ```
*
* When linking to this `User` route, you can write:
@ -34,22 +35,19 @@ import {Router} from '../router';
@Directive({selector: '[routerLink]'})
export class RouterLink {
@Input() target: string;
private commands: any[]|null = null;
private absoluteUrl: string|null = null;
private commands: any[] = [];
// the url displayed on the anchor element.
@HostBinding() href: string;
constructor(private router: Router) {}
constructor(private router: Router, private route: ActivatedRoute) {}
@Input()
set routerLink(data: any[] | string) {
if (Array.isArray(data)) {
this.commands = data;
this.absoluteUrl = null;
} else {
this.commands = null;
this.absoluteUrl = data;
this.commands = [data];
}
this.updateTargetUrlAndHref();
}
@ -59,15 +57,16 @@ export class RouterLink {
onClick(): boolean {
// If no target, or if target is _self, prevent default browser behavior
if (!(typeof this.target === "string") || this.target == '_self') {
this.router.navigateByUrl(this.absoluteUrl);
this.router.navigate(this.commands, {relativeTo: this.route});
return false;
}
return true;
}
private updateTargetUrlAndHref(): void {
if (this.absoluteUrl) {
this.href = this.absoluteUrl;
const tree = this.router.createUrlTree(this.commands, {relativeTo: this.route});
if (tree) {
this.href = this.router.serializeUrl(tree);
}
}
}

View File

@ -1,6 +1,6 @@
import {Directive, ViewContainerRef, Attribute, ComponentRef, ComponentFactory, ResolvedReflectiveProvider, ReflectiveInjector} from '@angular/core';
import {RouterOutletMap} from '../router_outlet_map';
import {PRIMARY_OUTLET} from '../router_state';
import {PRIMARY_OUTLET} from '../shared';
@Directive({selector: 'router-outlet'})
export class RouterOutlet {

View File

@ -4,18 +4,29 @@ import { UrlSerializer } from './url_serializer';
import { RouterOutletMap } from './router_outlet_map';
import { recognize } from './recognize';
import { rootNode, TreeNode } from './utils/tree';
import { UrlTree } from './url_tree';
import { createEmptyState, RouterState, ActivatedRoute, PRIMARY_OUTLET } from './router_state';
import { UrlTree, createEmptyUrlTree } from './url_tree';
import { PRIMARY_OUTLET, Params } from './shared';
import { createEmptyState, RouterState, ActivatedRoute} from './router_state';
import { RouterConfig } from './config';
import { RouterOutlet } from './directives/router_outlet';
import { createUrlTree } from './create_url_tree';
import { forEach } from './utils/collection';
import { Observable } from 'rxjs/Observable';
import { Subscription } from 'rxjs/Subscription';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/mergeMap';
import 'rxjs/add/operator/toPromise';
import {fromPromise} from 'rxjs/observable/fromPromise';
import {forkJoin} from 'rxjs/observable/forkJoin';
export interface NavigationExtras { relativeTo?: ActivatedRoute; queryParameters?: Params; fragment?: string; }
/**
* The `Router` is responsible for mapping URLs to components.
*/
export class Router {
private currentState: RouterState;
private currentUrlTree: UrlTree;
private currentRouterState: RouterState;
private config: RouterConfig;
private locationSubscription: Subscription;
@ -23,7 +34,8 @@ export class Router {
* @internal
*/
constructor(private rootComponent:Object, private resolver: ComponentResolver, private urlSerializer: UrlSerializer, private outletMap: RouterOutletMap, private location: Location) {
this.currentState = createEmptyState(<any>rootComponent.constructor);
this.currentUrlTree = createEmptyUrlTree();
this.currentRouterState = createEmptyState(<any>rootComponent.constructor);
this.setUpLocationChangeListener();
this.navigateByUrl(this.location.path());
}
@ -32,7 +44,14 @@ export class Router {
* Returns the current route state.
*/
get routerState(): RouterState {
return this.currentState;
return this.currentRouterState;
}
/**
* Returns the current url tree.
*/
get urlTree(): UrlTree {
return this.currentUrlTree;
}
/**
@ -44,9 +63,9 @@ export class Router {
* router.navigateByUrl("/team/33/user/11");
* ```
*/
navigateByUrl(url: string): void {
navigateByUrl(url: string): Observable<void> {
const urlTree = this.urlSerializer.parse(url);
this.navigate(urlTree, false);
return this.runNavigate(urlTree, false);
}
/**
@ -56,9 +75,9 @@ export class Router {
*
* ```
* router.resetConfig([
* { name: 'team', path: 'team/:id', component: TeamCmp, children: [
* { name: 'simple', path: 'simple', component: SimpleCmp },
* { name: 'user', path: 'user/:name', component: UserCmp }
* { path: 'team/:id', component: TeamCmp, children: [
* { path: 'simple', component: SimpleCmp },
* { path: 'user/:name', component: UserCmp }
* ] }
* ]);
* ```
@ -72,65 +91,134 @@ export class Router {
*/
dispose(): void { this.locationSubscription.unsubscribe(); }
/**
* Applies an array of commands to the current url tree and creates
* a new url tree.
*
* When given an activate route, applies the given commands starting from the route.
* When not given a route, applies the given command starting from the root.
*
* ### Usage
*
* ```
* // create /team/33/user/11
* router.createUrlTree(['/team', 33, 'user', 11]);
*
* // create /team/33;expand=true/user/11
* router.createUrlTree(['/team', 33, {expand: true}, 'user', 11]);
*
* // you can collapse static fragments like this
* router.createUrlTree(['/team/33/user', userId]);
*
* // assuming the current url is `/team/33/user/11` and the route points to `user/11`
*
* // navigate to /team/33/user/11/details
* router.createUrlTree(['details'], {relativeTo: route});
*
* // navigate to /team/33/user/22
* router.createUrlTree(['../22'], {relativeTo: route});
*
* // navigate to /team/44/user/22
* router.createUrlTree(['../../team/44/user/22'], {relativeTo: route});
* ```
*/
createUrlTree(commands: any[], {relativeTo, queryParameters, fragment}: NavigationExtras = {}): UrlTree {
const a = relativeTo ? relativeTo : this.routerState.root;
return createUrlTree(a, this.currentUrlTree, commands, queryParameters, fragment);
}
/**
* Navigate based on the provided array of commands and a starting point.
* If no starting route is provided, the navigation is absolute.
*
* ### Usage
*
* ```
* router.navigate(['team', 33, 'team', '11], {relativeTo: route});
* ```
*/
navigate(commands: any[], extras: NavigationExtras = {}): Observable<void> {
return this.runNavigate(this.createUrlTree(commands, extras));
}
/**
* Serializes a {@link UrlTree} into a string.
*/
serializeUrl(url: UrlTree): string { return this.urlSerializer.serialize(url); }
/**
* Parse a string into a {@link UrlTree}.
*/
parseUrl(url: string): UrlTree { return this.urlSerializer.parse(url); }
private setUpLocationChangeListener(): void {
this.locationSubscription = <any>this.location.subscribe((change) => {
this.navigate(this.urlSerializer.parse(change['url']), change['pop'])
this.runNavigate(this.urlSerializer.parse(change['url']), change['pop'])
});
}
private navigate(url: UrlTree, pop?: boolean): Promise<void> {
return recognize(this.resolver, this.config, url, this.currentState).then(newState => {
new ActivateRoutes(newState, this.currentState).activate(this.outletMap);
this.currentState = newState;
if (!pop) {
this.location.go(this.urlSerializer.serialize(url));
}
}).catch(e => console.log("error", e.message));
private runNavigate(url:UrlTree, pop?:boolean):Observable<void> {
const r = recognize(this.config, url, this.currentRouterState).mergeMap((newState:RouterState) => {
return new ActivateRoutes(this.resolver, newState, this.currentRouterState).activate(this.outletMap).map(() => {
this.currentUrlTree = url;
this.currentRouterState = newState;
if (!pop) {
this.location.go(this.urlSerializer.serialize(url));
}
});
});
r.subscribe((a) => {}, (e) => {}, () => {}); // force execution
return r;
}
}
class ActivateRoutes {
constructor(private futureState: RouterState, private currState: RouterState) {}
constructor(private resolver: ComponentResolver, private futureState: RouterState, private currState: RouterState) {}
activate(parentOutletMap: RouterOutletMap): void {
activate(parentOutletMap: RouterOutletMap): Observable<void> {
const currRoot = this.currState ? rootNode(this.currState) : null;
const futureRoot = rootNode(this.futureState);
this.activateChildRoutes(futureRoot, currRoot, parentOutletMap);
return this.activateChildRoutes(futureRoot, currRoot, parentOutletMap);
}
private activateChildRoutes(futureNode: TreeNode<ActivatedRoute>,
currNode: TreeNode<ActivatedRoute> | null,
outletMap: RouterOutletMap): void {
outletMap: RouterOutletMap): Observable<any> {
const prevChildren = nodeChildrenAsMap(currNode);
const observables = [];
futureNode.children.forEach(c => {
this.activateRoutes(c, prevChildren[c.value.outlet], outletMap);
observables.push(this.activateRoutes(c, prevChildren[c.value.outlet], outletMap).toPromise());
delete prevChildren[c.value.outlet];
});
forEach(prevChildren, (v, k) => this.deactivateOutletAndItChildren(outletMap._outlets[k]));
return forkJoin(observables);
}
activateRoutes(futureNode: TreeNode<ActivatedRoute>, currNode: TreeNode<ActivatedRoute>,
parentOutletMap: RouterOutletMap): void {
parentOutletMap: RouterOutletMap): Observable<void> {
const future = futureNode.value;
const curr = currNode ? currNode.value : null;
const outlet = getOutlet(parentOutletMap, futureNode.value);
if (future === curr) {
this.activateChildRoutes(futureNode, currNode, outlet.outletMap);
return this.activateChildRoutes(futureNode, currNode, outlet.outletMap);
} else {
this.deactivateOutletAndItChildren(outlet);
const outletMap = new RouterOutletMap();
this.activateNewRoutes(outletMap, future, outlet);
this.activateChildRoutes(futureNode, currNode, outletMap);
return this.activateNewRoutes(outletMap, future, outlet).mergeMap(() =>
this.activateChildRoutes(futureNode, currNode, outletMap));
}
}
private activateNewRoutes(outletMap: RouterOutletMap, future: ActivatedRoute, outlet: RouterOutlet): void {
private activateNewRoutes(outletMap: RouterOutletMap, future: ActivatedRoute, outlet: RouterOutlet): Observable<void> {
const resolved = ReflectiveInjector.resolve([
{provide: ActivatedRoute, useValue: future},
{provide: RouterOutletMap, useValue: outletMap}
]);
outlet.activate(future.factory, resolved, outletMap);
return fromPromise(this.resolver.resolveComponent(<any>future.component)).
map(factory => outlet.activate(factory, resolved, outletMap));
}
private deactivateOutletAndItChildren(outlet: RouterOutlet): void {

View File

@ -29,16 +29,18 @@ describe("Integration", () => {
useFactory: (resolver, urlSerializer, outletMap, location) =>
new Router(new RootCmp(), resolver, urlSerializer, outletMap, location),
deps: [ComponentResolver, UrlSerializer, RouterOutletMap, Location]
}
},
{provide: ActivatedRoute, useFactory: (r) => r.routerState.root, deps: [Router]},
]);
it('should update location when navigating',
fakeAsync(inject([Router, TestComponentBuilder, Location], (router, tcb, location) => {
router.resetConfig([
{ name: 'team', path: 'team/:id', component: TeamCmp }
{ path: 'team/:id', component: TeamCmp }
]);
const fixture = tcb.createFakeAsync(RootCmp);
advance(fixture);
router.navigateByUrl('/team/22');
advance(fixture);
@ -53,9 +55,9 @@ describe("Integration", () => {
xit('should navigate back and forward',
fakeAsync(inject([Router, TestComponentBuilder, Location], (router, tcb, location) => {
router.resetConfig([
{ name: 'team', path: 'team/:id', component: TeamCmp, children: [
{ name: 'simple', path: 'simple', component: SimpleCmp },
{ name: 'user', path: 'user/:name', component: UserCmp }
{ path: 'team/:id', component: TeamCmp, children: [
{ path: 'simple', component: SimpleCmp },
{ path: 'user/:name', component: UserCmp }
] }
]);
@ -80,8 +82,8 @@ describe("Integration", () => {
it('should navigate when locations changes',
fakeAsync(inject([Router, TestComponentBuilder, Location], (router, tcb, location) => {
router.resetConfig([
{ name: 'team', path: 'team/:id', component: TeamCmp, children: [
{ name: 'user', path: 'user/:name', component: UserCmp }
{ path: 'team/:id', component: TeamCmp, children: [
{ path: 'user/:name', component: UserCmp }
] }
]);
@ -99,15 +101,15 @@ describe("Integration", () => {
it('should support secondary routes',
fakeAsync(inject([Router, TestComponentBuilder], (router, tcb) => {
router.resetConfig([
{ name: 'team', path: 'team/:id', component: TeamCmp, children: [
{ name: 'user', path: 'user/:name', component: UserCmp },
{ name: 'simple', path: 'simple', component: SimpleCmp, outlet: 'right' }
{ path: 'team/:id', component: TeamCmp, children: [
{ path: 'user/:name', component: UserCmp },
{ path: 'simple', component: SimpleCmp, outlet: 'right' }
] }
]);
const fixture = tcb.createFakeAsync(RootCmp);
router.navigateByUrl('/team/22/user/victor(simple)');
router.navigateByUrl('/team/22/user/victor(right:simple)');
advance(fixture);
expect(fixture.debugElement.nativeElement)
@ -117,15 +119,15 @@ describe("Integration", () => {
it('should deactivate outlets',
fakeAsync(inject([Router, TestComponentBuilder], (router, tcb) => {
router.resetConfig([
{ name: 'team', path: 'team/:id', component: TeamCmp, children: [
{ name: 'user', path: 'user/:name', component: UserCmp },
{ name: 'simple', path: 'simple', component: SimpleCmp, outlet: 'right' }
{ path: 'team/:id', component: TeamCmp, children: [
{ path: 'user/:name', component: UserCmp },
{ path: 'simple', component: SimpleCmp, outlet: 'right' }
] }
]);
const fixture = tcb.createFakeAsync(RootCmp);
router.navigateByUrl('/team/22/user/victor(simple)');
router.navigateByUrl('/team/22/user/victor(right:simple)');
advance(fixture);
router.navigateByUrl('/team/22/user/victor');
@ -137,15 +139,15 @@ describe("Integration", () => {
it('should deactivate nested outlets',
fakeAsync(inject([Router, TestComponentBuilder], (router, tcb) => {
router.resetConfig([
{ name: 'team', path: 'team/:id', component: TeamCmp, children: [
{ name: 'user', path: 'user/:name', component: UserCmp },
{ name: 'simple', path: 'simple', component: SimpleCmp, outlet: 'right' }
{ path: 'team/:id', component: TeamCmp, children: [
{ path: 'user/:name', component: UserCmp },
{ path: 'simple', component: SimpleCmp, outlet: 'right' }
] }
]);
const fixture = tcb.createFakeAsync(RootCmp);
router.navigateByUrl('/team/22/user/victor(simple)');
router.navigateByUrl('/team/22/user/victor(right:simple)');
advance(fixture);
router.navigateByUrl('/');
@ -158,9 +160,9 @@ describe("Integration", () => {
it("should support string router links",
fakeAsync(inject([Router, TestComponentBuilder], (router, tcb) => {
router.resetConfig([
{ name: 'team', path: 'team/:id', component: TeamCmp, children: [
{ name: 'link', path: 'link', component: StringLinkCmp },
{ name: 'simple', path: 'simple', component: SimpleCmp }
{ path: 'team/:id', component: TeamCmp, children: [
{ path: 'link', component: StringLinkCmp },
{ path: 'simple', component: SimpleCmp }
] }
]);
@ -178,6 +180,63 @@ describe("Integration", () => {
expect(fixture.debugElement.nativeElement).toHaveText('team 33 { simple, right: }');
})));
it("should support absolute router links",
fakeAsync(inject([Router, TestComponentBuilder], (router, tcb) => {
router.resetConfig([
{ path: 'team/:id', component: TeamCmp, children: [
{ path: 'link', component: AbsoluteLinkCmp },
{ path: 'simple', component: SimpleCmp }
] }
]);
const fixture = tcb.createFakeAsync(RootCmp);
advance(fixture);
router.navigateByUrl('/team/22/link');
advance(fixture);
expect(fixture.debugElement.nativeElement).toHaveText('team 22 { link, right: }');
const native = fixture.debugElement.nativeElement.querySelector("a");
expect(native.getAttribute("href")).toEqual("/team/33/simple");
native.click();
advance(fixture);
expect(fixture.debugElement.nativeElement).toHaveText('team 33 { simple, right: }');
})));
it("should support relative router links",
fakeAsync(inject([Router, TestComponentBuilder], (router, tcb) => {
router.resetConfig([
{ path: 'team/:id', component: TeamCmp, children: [
{ path: 'link', component: RelativeLinkCmp },
{ path: 'simple', component: SimpleCmp }
] }
]);
const fixture = tcb.createFakeAsync(RootCmp);
advance(fixture);
router.navigateByUrl('/team/22/link');
advance(fixture);
expect(fixture.debugElement.nativeElement)
.toHaveText('team 22 { link, right: }');
const native = fixture.debugElement.nativeElement.querySelector("a");
expect(native.getAttribute("href")).toEqual("/team/22/simple");
native.click();
advance(fixture);
expect(fixture.debugElement.nativeElement)
.toHaveText('team 22 { simple, right: }');
})));
it("should support top-level link",
fakeAsync(inject([Router, TestComponentBuilder], (router, tcb) => {
let fixture = tcb.createFakeAsync(AbsoluteLinkCmp);
advance(fixture);
expect(fixture.debugElement.nativeElement).toHaveText('link');
})));
});
});
@ -188,6 +247,20 @@ describe("Integration", () => {
})
class StringLinkCmp {}
@Component({
selector: 'link-cmp',
template: `<a [routerLink]="['/team/33/simple']">link</a>`,
directives: ROUTER_DIRECTIVES
})
class AbsoluteLinkCmp {}
@Component({
selector: 'link-cmp',
template: `<a [routerLink]="['../simple']">link</a>`,
directives: ROUTER_DIRECTIVES
})
class RelativeLinkCmp {}
@Component({
selector: 'simple-cmp',
template: `simple`,

View File

@ -22,6 +22,7 @@
"src/router_state.ts",
"src/url_serializer.ts",
"src/url_tree.ts",
"src/create_url_tree.ts",
"src/directives/router_outlet.ts",
"src/directives/router_link.ts",
"src/utils/tree.ts",
@ -29,6 +30,7 @@
"test/utils/tree.spec.ts",
"test/url_serializer.spec.ts",
"test/recognize.spec.ts",
"test/create_url_tree.spec.ts",
"test/router.spec.ts",
"typings/index.d.ts"
]