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

Added "nf-tools" #398

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
6 changes: 6 additions & 0 deletions libs/native-federation-runtime/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@
export * from './lib/init-federation';
export * from './lib/load-remote-module';
export * from './lib/bootstrap-utils';
export * from './lib/web-component-wrapper';
export * from './lib/router-utils';
export * from './lib/model/federation-info';
export * from './lib/model/bootstrap-federated-application-options';
export * from './lib/model/bootstrap-federated-webcomponent-options';
export * from './lib/model/web-component-wrapper-options';
72 changes: 72 additions & 0 deletions libs/native-federation-runtime/src/lib/bootstrap-utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import { ApplicationConfig, ApplicationRef, NgZone, Type, reflectComponentType } from '@angular/core';
import { bootstrapApplication, createApplication } from '@angular/platform-browser';
import { Router } from '@angular/router';
import { NgElementConstructor, createCustomElement } from '@angular/elements';
import { connectRouter } from './router-utils';
import { BootstrapFederatedApplicationOptions } from './model/bootstrap-federated-application-options';
import { BootstrapFederatedWebComponentOptions } from './model/bootstrap-federated-webcomponent-options';

export function bootstrapFederatedApplication<TRootComponent>(
component: Type<TRootComponent>,
appConfig: ApplicationConfig,
options: BootstrapFederatedApplicationOptions,
): Promise<ApplicationRef> {
let { appType, enableNgZoneSharing } = options;
enableNgZoneSharing = enableNgZoneSharing !== false;
if (enableNgZoneSharing && appType === 'microfrontend') {
const ngZoneProvider = (globalThis as any).ngZone ? { provide: NgZone, useValue: (globalThis as any).ngZone } : [];
appConfig = { ...appConfig };
appConfig.providers = [ngZoneProvider, ...appConfig.providers];
}
return bootstrapApplication(component, appConfig).then((appRef: ApplicationRef) => {
if (appType === 'shell') {
if (enableNgZoneSharing) {
const ngZone = appRef.injector.get(NgZone);
if (ngZone) {
(globalThis as any).ngZone = ngZone;
}
}
} else if (appType === 'microfrontend') {
const router = appRef.injector.get(Router);
if (router) {
const useHash = location.href.includes('#');
connectRouter(router, useHash);
}
}
return appRef;
});
}

export function bootstrapFederatedWebComponent<TRootComponent>(
component: Type<TRootComponent>,
appConfig: ApplicationConfig,
options: BootstrapFederatedWebComponentOptions,
): Promise<{ appRef: ApplicationRef; elementCtr: NgElementConstructor<TRootComponent> }> {
let { appType, enableNgZoneSharing } = options;
enableNgZoneSharing = enableNgZoneSharing !== false;
if (enableNgZoneSharing && appType === 'microfrontend') {
const ngZoneProvider = (globalThis as any).ngZone ? { provide: NgZone, useValue: (globalThis as any).ngZone } : [];
appConfig = { ...appConfig };
appConfig.providers = [ngZoneProvider, ...appConfig.providers];
}
return createApplication(appConfig).then((appRef: ApplicationRef) => {
if (appType === 'shell') {
if (enableNgZoneSharing) {
const ngZone = appRef.injector.get(NgZone);
if (ngZone) {
(globalThis as any).ngZone = ngZone;
}
}
} else if (appType === 'microfrontend') {
const router = appRef.injector.get(Router);
if (router) {
const useHash = location.href.includes('#');
connectRouter(router, useHash);
}
}
const elementCtr = createCustomElement<TRootComponent>(component, { injector: appRef.injector });
const componentType = reflectComponentType(component);
customElements.define(componentType?.selector || options.elementName, elementCtr);
return { appRef, elementCtr };
});
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
export type AppType = 'shell' | 'microfrontend';

export type BootstrapFederatedApplicationOptions = {
appType: AppType;
enableNgZoneSharing?: boolean;
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import { BootstrapFederatedApplicationOptions } from './bootstrap-federated-application-options';
import { WebComponentOptions } from './web-component-options';

export type BootstrapFederatedWebComponentOptions = BootstrapFederatedApplicationOptions & WebComponentOptions;
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export type WebComponentOptions = {
elementName: string;
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import { LoadRemoteModuleOptions } from '@angular-architects/native-federation';
import { WebComponentOptions } from './web-component-options';

export type WebComponentWrapperOptions = LoadRemoteModuleOptions & WebComponentOptions;
38 changes: 38 additions & 0 deletions libs/native-federation-runtime/src/lib/router-utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { Router, UrlMatcher, UrlSegment } from '@angular/router';

const flatten = (url: UrlSegment[]): string => url.map((u) => u.path).join('/');

export function startsWith(prefix: string): UrlMatcher {
return (url: UrlSegment[]) => {
if (flatten(url).startsWith(prefix)) {
return { consumed: url };
}
return null;
};
}

export function endsWith(prefix: string): UrlMatcher {
return (url: UrlSegment[]) => {
if (flatten(url).endsWith(prefix)) {
return { consumed: url };
}
return null;
};
}

export function connectRouter(router: Router, useHash = false): void {
let url: string;
if (!useHash) {
url = `${location.pathname.substring(1)}${location.search}`;
router.navigateByUrl(url);
window.addEventListener('popstate', () => {
router.navigateByUrl(url);
});
} else {
url = `${location.hash.substring(1)}${location.search}`;
router.navigateByUrl(url);
window.addEventListener('hashchange', () => {
router.navigateByUrl(url);
});
}
}
72 changes: 72 additions & 0 deletions libs/native-federation-runtime/src/lib/web-component-wrapper.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import { OnInit, Component, ElementRef, Input, OnChanges, SimpleChanges, ViewChild, inject } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { loadRemoteModule } from '@angular-architects/native-federation';
import { WebComponentWrapperOptions } from './model/web-component-wrapper-options';
import { CommonModule } from '@angular/common';

type EventHandlers = { [event: string]: (event: Event) => void };

@Component({
selector: 'web-component-wrapper',
standalone: true,
imports: [CommonModule],
template: `<div #host></div>`,
})
export class WebComponentWrapper implements OnChanges, OnInit {
@ViewChild('host', { read: ElementRef, static: true }) host: ElementRef | undefined;

@Input() config: WebComponentWrapperOptions | undefined;
@Input() props: { [prop: string]: unknown } | undefined;
@Input() handlers: EventHandlers| undefined;

webComponent: HTMLElement | undefined;
protected route = inject(ActivatedRoute);

async ngOnInit(): Promise<void> {
await this.loadWebComponent();
}

async ngOnChanges(changes: SimpleChanges): Promise<void> {
if (!this.webComponent) return;
const { config, handlers } = changes;
if (config?.previousValue !== config?.currentValue && config?.currentValue) {
await this.loadWebComponent();
}
if (handlers?.previousValue !== handlers?.currentValue && handlers?.previousValue) {
this.unbindEventHandlers(handlers.previousValue);
}
this.bindEventHandlers();
this.bindProps();
}

protected async loadWebComponent(): Promise<void> {
const config = this.config || (this.route.snapshot.data as WebComponentWrapperOptions);
if (!config) return;
await loadRemoteModule(config);
this.webComponent = document.createElement(config.elementName);
this.bindProps();
this.bindEventHandlers();
this.host!.nativeElement.appendChild(this.webComponent);
}

protected bindProps(): void {
if (!this.webComponent) return;
for (const prop in this.props) {
(this.webComponent as any)[prop] = this.props[prop];
}
}

protected bindEventHandlers(): void {
if (!this.webComponent) return;
for (const event in this.handlers) {
this.webComponent.addEventListener(event, this.handlers[event]);
}
}

protected unbindEventHandlers(handlers: EventHandlers): void {
if (!this.webComponent) return;
for (const event in handlers) {
this.webComponent.removeEventListener(event, handlers[event]);
}
}
}
16 changes: 16 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 3 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
"@angular/common": "17.0.2",
"@angular/compiler": "17.0.2",
"@angular/core": "17.0.2",
"@angular/elements": "^17.0.2",
"@angular/forms": "17.0.2",
"@angular/platform-browser": "17.0.2",
"@angular/platform-browser-dynamic": "17.0.2",
Expand Down Expand Up @@ -68,6 +69,7 @@
"@nx/angular": "17.1.1",
"@nx/cypress": "17.1.1",
"@nx/devkit": "17.1.1",
"@nx/eslint": "17.1.1",
"@nx/eslint-plugin": "17.1.1",
"@nx/jest": "17.1.1",
"@nx/js": "17.1.1",
Expand Down Expand Up @@ -119,8 +121,7 @@
"ts-node": "10.9.1",
"tslib": "^2.3.0",
"typescript": "~5.2.0",
"verdaccio": "^5.0.4",
"@nx/eslint": "17.1.1"
"verdaccio": "^5.0.4"
},
"nx": {
"includedScripts": []
Expand Down