Skip to content
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

feat: supporting input binding feature #141

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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: 9 additions & 3 deletions apps/nativescript-demo-ng/src/app/app-routing.module.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,22 @@
import { NgModule } from '@angular/core';
import { Routes } from '@angular/router';
import { NativeScriptRouterModule } from '@nativescript/angular';

import { dummyDataResolverTsResolver } from './input-bidings/dummy-data.resolver.ts.resolver';
import { ItemDetailComponent } from './item/item-detail.component';
import { ItemsComponent } from './item/items.component';
// import { HomeComponent } from './home/home.component';
// import { BootGuardService } from './boot-guard.service';

const routes: Routes = [
{ path: '', redirectTo: '/rootlazy', pathMatch: 'full' },
{ path: '', redirectTo: '/redirect', pathMatch: 'full' },
{ path: 'items', component: ItemsComponent },
{ path: 'item/:id', component: ItemDetailComponent },
{ path: 'item2', loadChildren: () => import('./item2/item2.module').then((m) => m.Item2Module) },
{ path: 'rootlazy', loadChildren: () => import('./item3/item3.module').then((m) => m.Item3Module) },
{ path: 'redirect', loadComponent: () => import('./input-bidings/redirect-page.component').then((c) => c.RedirectPage) },
{ path: 'bindings/:name', loadComponent: () => import('./input-bidings/input-bidings.component').then((c) => c.InputBidingsComponent), resolve: {
data: dummyDataResolverTsResolver
} },

/**
* Test tab named outlets
Expand All @@ -38,7 +42,9 @@ const routes: Routes = [
];

@NgModule({
imports: [NativeScriptRouterModule.forRoot(routes)],
imports: [NativeScriptRouterModule.forRoot(routes, {
bindToComponentInputs: true,
})],
exports: [NativeScriptRouterModule],
})
export class AppRoutingModule {}
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import type { ResolveFn } from '@angular/router';
import { of } from 'rxjs';

export const dummyDataResolverTsResolver: ResolveFn<string[]> = (route, state) => {
return of(['Name1', 'Name2', "Name3"]);
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
:host {
display: block;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@

<StackLayout>
<Label [text]="'Name (routerparam): '+name()"></Label>
<Label [text]="'Id (queryparam): '+id()"></Label>
@for(name of data(); track name) {
<Label [text]="'item - '+name"></Label>
}
<Button text="Redirect to other route" (tap)="navigationTo()"></Button>
</StackLayout>
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { ChangeDetectionStrategy, Component, inject, input, NO_ERRORS_SCHEMA } from '@angular/core';
import { NativeScriptCommonModule, RouterExtensions } from '../../../../../packages/angular/src';

@Component({
selector: 'app-input-bidings',
standalone: true,
imports: [
NativeScriptCommonModule,
],
templateUrl: `./input-bidings.component.html`,
styleUrl: './input-bidings.component.css',
changeDetection: ChangeDetectionStrategy.OnPush,
schemas: [NO_ERRORS_SCHEMA]
})
export class InputBidingsComponent {

protected readonly router = inject(RouterExtensions)

name = input(); //Route param

id = input(); //Query param

data = input<string[]>(); // Resolver

navigationTo() {
this.router.navigate(['/bindings/testing2/'], { queryParams: { id: 10}})
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { ChangeDetectionStrategy, Component, inject, NO_ERRORS_SCHEMA } from "@angular/core"
import { NativeScriptCommonModule, NativeScriptRouterModule, RouterExtensions } from "../../../../../packages/angular/src"

@Component({
selector: 'app-input-bidings',
standalone: true,
imports: [
NativeScriptCommonModule, NativeScriptRouterModule,
],
template: `<Label text="Redirecting">`,
changeDetection: ChangeDetectionStrategy.OnPush,
schemas: [NO_ERRORS_SCHEMA]
})
export class RedirectPage {

protected readonly router = inject(RouterExtensions)

constructor() {
this.router.navigate(['/bindings/test/'], { queryParams: { id: 1}, clearHistory: true})
}
}

12 changes: 12 additions & 0 deletions packages/angular/src/lib/legacy/router/page-router-outlet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import { findTopActivatedRouteNodeForOutlet, pageRouterActivatedSymbol, loaderRe
import { registerElement } from '../../element-registry';
import { PageService } from '../../cdk/frame-page/page.service';
import { ExtendedNavigationExtras } from './router-extensions';
import { INPUT_BINDER } from '../../router/router-component-input-binder';

export class PageRoute {
activatedRoute: BehaviorSubject<ActivatedRoute>;
Expand Down Expand Up @@ -146,6 +147,13 @@ export class PageRouterOutlet implements OnDestroy, RouterOutletContract {
return {};
}

/** @internal */
get activatedComponentRef(): ComponentRef<any> | null {
return this.activated;
}

private inputBinder = inject(INPUT_BINDER, { optional: true });

constructor(
private parentContexts: ChildrenOutletContexts,
private location: ViewContainerRef,
Expand Down Expand Up @@ -176,6 +184,7 @@ export class PageRouterOutlet implements OnDestroy, RouterOutletContract {

this.viewUtil = viewUtil;
this.detachedLoaderFactory = resolver.resolveComponentFactory(DetachedLoader);

}

setActionBarVisibility(actionBarVisibility: string): void {
Expand Down Expand Up @@ -217,6 +226,8 @@ export class PageRouterOutlet implements OnDestroy, RouterOutletContract {
this.deactivateEvents.emit(c);
this.activated = null;
}

this.inputBinder?.unsubscribeFromRouteData(this);
}

deactivate(): void {
Expand Down Expand Up @@ -345,6 +356,7 @@ export class PageRouterOutlet implements OnDestroy, RouterOutletContract {
this.markActivatedRoute(activatedRoute);

this.activateOnGoForward(activatedRoute, resolver || this.environmentInjector);
this.inputBinder?.bindActivatedRouteToOutletComponent(this);
this.activateEvents.emit(this.activated.instance);
}

Expand Down
2 changes: 2 additions & 0 deletions packages/angular/src/lib/legacy/router/router.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { FrameService } from '../frame.service';
import { NSEmptyOutletComponent } from './ns-empty-outlet.component';
import { NativeScriptCommonModule } from '../../nativescript-common.module';
import { START_PATH } from '../../tokens';
import { withComponentInputBinding } from '../../router/router-component-input-binder';

export { PageRoute } from './page-router-outlet';
export { RouterExtensions } from './router-extensions';
Expand Down Expand Up @@ -50,6 +51,7 @@ export class NativeScriptRouterModule {
RouterExtensions,
NSRouteReuseStrategy,
{ provide: RouteReuseStrategy, useExisting: NSRouteReuseStrategy },
config?.bindToComponentInputs ? withComponentInputBinding().ɵproviders : [],
],
};
}
Expand Down
122 changes: 122 additions & 0 deletions packages/angular/src/lib/router/router-component-input-binder.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
import { Injectable, InjectionToken, Provider, reflectComponentType } from "@angular/core";
import { Router, RouterOutlet } from "@angular/router";
import { PageRouterOutlet } from "@nativescript/angular";
import { combineLatest, of, Subscription, switchMap } from "rxjs";
import { NativeScriptDebug } from "../trace";

export const INPUT_BINDER = new InjectionToken<RoutedComponentInputBinder>('');
/**
* Injectable used as a tree-shakable provider for opting in to binding router data to component
* inputs.
*
* The RouterOutlet registers itself with this service when an `ActivatedRoute` is attached or
* activated. When this happens, the service subscribes to the `ActivatedRoute` observables (params,
* queryParams, data) and sets the inputs of the component using `ComponentRef.setInput`.
* Importantly, when an input does not have an item in the route data with a matching key, this
* input is set to `undefined`. If it were not done this way, the previous information would be
* retained if the data got removed from the route (i.e. if a query parameter is removed).
*
* The `RouterOutlet` should unregister itself when destroyed via `unsubscribeFromRouteData` so that
* the subscriptions are cleaned up.
*/
@Injectable()
export class RoutedComponentInputBinder {
private outletDataSubscriptions = new Map<PageRouterOutlet, Subscription>;

bindActivatedRouteToOutletComponent(outlet: PageRouterOutlet): void {
this.unsubscribeFromRouteData(outlet);
this.subscribeToRouteData(outlet);
}

unsubscribeFromRouteData(outlet: PageRouterOutlet): void {
this.outletDataSubscriptions.get(outlet)?.unsubscribe();
this.outletDataSubscriptions.delete(outlet);
}

private subscribeToRouteData(outlet: PageRouterOutlet) {

const { activatedRoute } = outlet;

if (!activatedRoute) {
if (NativeScriptDebug.isLogEnabled()) {
NativeScriptDebug.routerLog('Outlet is not activatedA');
}
return;
}

const dataSubscription =
combineLatest([
activatedRoute.queryParams,
activatedRoute.params,
activatedRoute.data,
])
.pipe(switchMap(([queryParams, params, data], index) => {
data = { ...queryParams, ...params, ...data };
// Get the first result from the data subscription synchronously so it's available to
// the component as soon as possible (and doesn't require a second change detection).
if (index === 0) {
return of(data);
}
// Promise.resolve is used to avoid synchronously writing the wrong data when
// two of the Observables in the `combineLatest` stream emit one after
// another.
return Promise.resolve(data);
}))
.subscribe(data => {
// Outlet may have been deactivated or changed names to be associated with a different
// route
if (!outlet.isActivated || !outlet.activatedComponentRef ||
outlet.activatedRoute !== activatedRoute || activatedRoute.component === null) {
this.unsubscribeFromRouteData(outlet);
return;
}

const mirror = reflectComponentType(activatedRoute.component);
if (!mirror) {
this.unsubscribeFromRouteData(outlet);
return;
}

for (const { templateName } of mirror.inputs) {
outlet.activatedComponentRef.setInput(templateName, data[templateName]);
}
});

this.outletDataSubscriptions.set(outlet, dataSubscription);
}
}

/**
* Enables binding information from the `Router` state directly to the inputs of the component in
* `Route` configurations.
*
*/
export function withComponentInputBinding(): {
ɵkind: number;
ɵproviders: Provider[];
} {
const providers = [
RoutedComponentInputBinder,
{ provide: INPUT_BINDER, useExisting: RoutedComponentInputBinder },
];

return {
ɵkind: RouterFeatureKind.ComponentInputBindingFeature,
ɵproviders: providers
}
}

/**
* The list of features as an enum to uniquely type each feature.
*/
export const enum RouterFeatureKind {
PreloadingFeature,
DebugTracingFeature,
EnabledBlockingInitialNavigationFeature,
DisabledInitialNavigationFeature,
InMemoryScrollingFeature,
RouterConfigurationFeature,
RouterHashLocationFeature,
NavigationErrorHandlerFeature,
ComponentInputBindingFeature,
}
Loading