Skip to content

Page router outlet and router directives #61

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Feb 10, 2016
Merged
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
12 changes: 10 additions & 2 deletions ng-sample/app/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,23 @@

// this import should be first in order to load some required settings (like globals and reflect-metadata)
import { nativeScriptBootstrap } from "./nativescript-angular/application";
import { NS_ROUTER_PROVIDERS, routerTraceCategory } from "./nativescript-angular/router/ns-router";

import trace = require("trace");
trace.setCategories(routerTraceCategory);
trace.enable();

//import {RendererTest} from './examples/renderer-test';
//import {Benchmark} from './performance/benchmark';
//import {ListTest} from './examples/list/list-test';
import {ListTestAsync} from "./examples/list/list-test-async";
// import {ListTestAsync} from "./examples/list/list-test-async";
// import {ImageTest} from "./examples/image/image-test";
import {NavigationTest} from "./examples/navigation/navigation-test";


//nativeScriptBootstrap(RendererTest);
//nativeScriptBootstrap(Benchmark);
//nativeScriptBootstrap(ListTest);
nativeScriptBootstrap(ListTestAsync);
// nativeScriptBootstrap(ListTestAsync);
// nativeScriptBootstrap(ImageTest);
nativeScriptBootstrap(NavigationTest, [NS_ROUTER_PROVIDERS]);
53 changes: 53 additions & 0 deletions ng-sample/app/examples/navigation/nav-component.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import {Component} from 'angular2/core';
import {OnActivate, OnDeactivate, LocationStrategy, RouteParams, ComponentInstruction } from 'angular2/router';
import {topmost} from "ui/frame";
import {NS_ROUTER_DIRECTIVES} from "../../nativescript-angular/router/ns-router";


@Component({
selector: 'example-group',
directives: [NS_ROUTER_DIRECTIVES],
template: `
<GridLayout rows="auto, auto, auto" columns="*, *" margin="10">
<Label [text]="'Componenet ID: ' + compId" colSpan="2" row="0"
style="font-size: 30; horizontal-align: center; margin: 10"></Label>

<Label [text]="'Depth: ' + depth" colSpan="2" row="1"
style="font-size: 30; horizontal-align: center; margin: 10"></Label>

<Button text="BACK" row="2" col="0" width="150"
(tap)="goBack()"></Button>

<Button text="FORWARD" row="2" col="1" width="150"
[nsRouterLink]="['/Nav', { depth: depth + 1 }]"></Button>
</GridLayout>
`
})
export class NavComponent implements OnActivate, OnDeactivate {
static counter: number = 0;

public compId: number;
public depth: number;

constructor(params: RouteParams, private location: LocationStrategy) {
NavComponent.counter++;

this.compId = NavComponent.counter;
this.depth = parseInt(params.get("depth"));

console.log("NavComponent.constructor() componenetID: " + this.compId)
}

public goBack() {
// this.location.back();
topmost().goBack();
}

routerOnActivate(nextInstruction: ComponentInstruction, prevInstruction: ComponentInstruction): any {
console.log("NavComponent.routerOnActivate() componenetID: " + this.compId)
}

routerOnDeactivate(nextInstruction: ComponentInstruction, prevInstruction: ComponentInstruction): any {
console.log("NavComponent.routerOnDeactivate() componenetID: " + this.compId)
}
}
29 changes: 29 additions & 0 deletions ng-sample/app/examples/navigation/navigation-test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import {Component} from 'angular2/core';
import {RouteConfig, ROUTER_PROVIDERS, ROUTER_DIRECTIVES} from 'angular2/router';

import {NavComponent} from "./nav-component";
import {NS_ROUTER_DIRECTIVES} from "../../nativescript-angular/router/ns-router";

@Component({
selector:"start-nav-test",
directives: [NS_ROUTER_DIRECTIVES],
template:`<Button horizontalAlignment="center" verticalAlignment="center" text="start" [nsRouterLink]="['/Nav', { depth: 1 }]"></Button>`
})
class StartComponent {

}


@Component({
selector: 'navigation-test',
directives: [NS_ROUTER_DIRECTIVES],
template: "<GridLayout><page-router-outlet></page-router-outlet></GridLayout>"
})
@RouteConfig([
{ path: '/', component: StartComponent, as: 'Start' },
{ path: '/nav/:depth', component: NavComponent, as: 'Nav' },
])
export class NavigationTest {

}

7 changes: 7 additions & 0 deletions src/nativescript-angular/router/common.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import trace = require("trace");

export const CATEGORY = "ns-router";

export function log(message: string) {
trace.write(message, CATEGORY);
}
90 changes: 90 additions & 0 deletions src/nativescript-angular/router/ns-location-strategy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
import application = require("application");
import { LocationStrategy } from 'angular2/router';
import { NgZone, ApplicationRef, Inject, forwardRef } from 'angular2/core';
import { log } from "./common";

interface LocationState
{
state: any,
title: string,
url: string,
queryParams: string
}

export class NSLocationStrategy extends LocationStrategy {
private states = new Array<LocationState>();
private popStateCallbacks = new Array<(_: any) => any>();
private ngZone: NgZone;
constructor(@Inject(forwardRef(() => NgZone)) zone: NgZone){
super();

this.ngZone = zone;
//if(application.android){
//application.android.on("activityBackPressed", (args: application.AndroidActivityBackPressedEventData) => {
//this.ngZone.run( () => {
//if(this.states.length > 1){
//this.back();
//args.cancel = true;
//}
//});
//})
//}
}

path(): string {
log("NSLocationStrategy.path()");
if(this.states.length > 0){
return this.states[this.states.length - 1].url;
}
return "/";
}
prepareExternalUrl(internal: string): string {
log("NSLocationStrategy.prepareExternalUrl() internal: " + internal);
return internal;
}
pushState(state: any, title: string, url: string, queryParams: string): void {
log(`NSLocationStrategy.pushState state: ${state}, title: ${title}, url: ${url}, queryParams: ${queryParams}`);

this.states.push({
state: state,
title: title,
url: url,
queryParams: queryParams });

}
replaceState(state: any, title: string, url: string, queryParams: string): void {
log(`NSLocationStrategy.replaceState state: ${state}, title: ${title}, url: ${url}, queryParams: ${queryParams}`);

this.states.pop()
this.states.push({
state: state,
title: title,
url: url,
queryParams: queryParams });
}
forward(): void {
log("NSLocationStrategy.forward");
throw new Error("Not implemented");
}
back(): void {
log("NSLocationStrategy.back");

var state = this.states.pop();
this.callPopState(state, true);
}
onPopState(fn: (_: any) => any): void {
log("NSLocationStrategy.onPopState");
this.popStateCallbacks.push(fn);
}
getBaseHref(): string {
log("NSLocationStrategy.getBaseHref()");
return "";
}

private callPopState(state:LocationState, pop: boolean = true){
var change = { url: state.url, pop: pop};
for(var fn of this.popStateCallbacks){
fn(change);
}
}
}
60 changes: 60 additions & 0 deletions src/nativescript-angular/router/ns-router-link.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import {Directive, Input} from 'angular2/core';
import {isString} from 'angular2/src/facade/lang';
import {Router, Location, Instruction} from 'angular2/router';
import { log } from "./common";

/**
* The NSRouterLink directive lets you link to specific parts of your app.
*
* Consider the following route configuration:
* ```
* @RouteConfig([
* { path: '/user', component: UserCmp, as: 'User' }
* ]);
* class MyComp {}
* ```
*
* When linking to this `User` route, you can write:
*
* ```
* <a [nsRouterLink]="['./User']">link to user component</a>
* ```
*
* RouterLink expects the value to be an array of route names, followed by the params
* for that level of routing. For instance `['/Team', {teamId: 1}, 'User', {userId: 2}]`
* means that we want to generate a link for the `Team` route with params `{teamId: 1}`,
* and with a child route `User` with params `{userId: 2}`.
*
* The first route name should be prepended with `/`, `./`, or `../`.
* If the route begins with `/`, the router will look up the route from the root of the app.
* If the route begins with `./`, the router will instead look in the current component's
* children for the route. And if the route begins with `../`, the router will look at the
* current component's parent.
*/
@Directive({
selector: '[nsRouterLink]',
inputs: ['params: nsRouterLink'],
host: {
'(tap)': 'onTap()'
}
})
export class NSRouterLink {
private _routeParams: any[];

// the instruction passed to the router to navigate
private _navigationInstruction: Instruction;

constructor(private _router: Router, private _location: Location) { }

// get isRouteActive(): boolean { return this._router.isRouteActive(this._navigationInstruction); }

set params(changes: any[]) {
this._routeParams = changes;
this._navigationInstruction = this._router.generate(this._routeParams);
}

onTap(): void {
log("NSRouterLink onTap() instruction: " + JSON.stringify(this._navigationInstruction))
this._router.navigateByInstruction(this._navigationInstruction);
}
}
19 changes: 19 additions & 0 deletions src/nativescript-angular/router/ns-router.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import {Type} from 'angular2/src/facade/lang';
import {NSRouterLink} from './ns-router-link';
import {PageRouterOutlet} from './page-router-outlet';
import {NSLocationStrategy} from './ns-location-strategy';
import {ROUTER_PROVIDERS, LocationStrategy} from 'angular2/router';
import {provide} from 'angular2/core';
import { CATEGORY } from "./common";

export const NS_ROUTER_PROVIDERS: any[] = [
ROUTER_PROVIDERS,
provide(LocationStrategy, {useClass: NSLocationStrategy})
];

export const NS_ROUTER_DIRECTIVES: Type[] = [
NSRouterLink,
PageRouterOutlet
];

export const routerTraceCategory = CATEGORY;
Loading