Skip to content
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
import { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing';
import { ActivatedRoute } from '@angular/router';

import { DotRemoteModuleWrapperComponent } from './dot-remote-module-wrapper.component';

describe('DotRemoteModuleWrapperComponent', () => {
let fixture: ComponentFixture<DotRemoteModuleWrapperComponent>;
let component: DotRemoteModuleWrapperComponent;
let mockCleanup: jest.Mock;
let mockMount: jest.Mock;

function createComponent(mountFn?: unknown): void {
TestBed.configureTestingModule({
imports: [DotRemoteModuleWrapperComponent],
providers: [
{
provide: ActivatedRoute,
useValue: {
snapshot: {
data: mountFn !== undefined ? { mount: mountFn } : {}
}
}
}
]
});

fixture = TestBed.createComponent(DotRemoteModuleWrapperComponent);
component = fixture.componentInstance;
}

beforeEach(() => {
mockCleanup = jest.fn();
mockMount = jest.fn().mockResolvedValue(mockCleanup);
});

it('should call mount with the container element', fakeAsync(() => {
createComponent(mockMount);
fixture.detectChanges();
tick();

expect(mockMount).toHaveBeenCalledWith(component.container.nativeElement);
}));

it('should store and call cleanup on destroy', fakeAsync(() => {
createComponent(mockMount);
fixture.detectChanges();
tick();

component.ngOnDestroy();

expect(mockCleanup).toHaveBeenCalled();
}));

it('should not throw when mount is not provided in route data', fakeAsync(() => {
createComponent();
fixture.detectChanges();
tick();

expect(mockMount).not.toHaveBeenCalled();
expect(() => component.ngOnDestroy()).not.toThrow();
}));

it('should handle mount error gracefully', fakeAsync(() => {
const errorMount = jest.fn().mockRejectedValue(new Error('mount failed'));
const consoleSpy = jest.spyOn(console, 'error').mockImplementation();

createComponent(errorMount);
fixture.detectChanges();
tick();

expect(consoleSpy).toHaveBeenCalledWith(
'[DotRemoteModuleWrapper] Failed to mount remote module:',
expect.any(Error)
);

// cleanup should not have been set
expect(() => component.ngOnDestroy()).not.toThrow();
consoleSpy.mockRestore();
}));

it('should handle cleanup error gracefully', fakeAsync(() => {
const throwingCleanup = jest.fn().mockImplementation(() => {
throw new Error('cleanup failed');
});
const errorMount = jest.fn().mockResolvedValue(throwingCleanup);
const consoleSpy = jest.spyOn(console, 'error').mockImplementation();

createComponent(errorMount);
fixture.detectChanges();
tick();

expect(() => component.ngOnDestroy()).not.toThrow();
expect(consoleSpy).toHaveBeenCalledWith(
'[DotRemoteModuleWrapper] Failed to unmount remote module:',
expect.any(Error)
);
consoleSpy.mockRestore();
}));
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import {
AfterViewInit,
Component,
ElementRef,
inject,
NgZone,
OnDestroy,
ViewChild
} from '@angular/core';
import { ActivatedRoute } from '@angular/router';

type MountFn = (el: HTMLElement) => Promise<() => void>;

/**
* Wrapper component that hosts a remote Module Federation module.
*
* Remote modules export a `mount(element)` function that bootstraps
* their own Angular app inside the provided DOM element. This component
* provides that element and manages the mount/unmount lifecycle.
*
* The mount is run outside of the host's NgZone to prevent zone conflicts
* between the host and remote Angular runtimes.
*/
@Component({
selector: 'dot-remote-module-wrapper',
standalone: true,
template: '<div #container style="width: 100%; height: 100%;"></div>'
})
export class DotRemoteModuleWrapperComponent implements AfterViewInit, OnDestroy {
@ViewChild('container', { static: true }) container!: ElementRef<HTMLElement>;

private readonly route = inject(ActivatedRoute);
private readonly ngZone = inject(NgZone);
private destroyFn?: () => void;

ngAfterViewInit(): void {
const mountFn = this.route.snapshot.data['mount'] as MountFn | undefined;

if (mountFn) {
// Run outside the host's NgZone so the remote Angular app
// bootstraps with its own zone and doesn't conflict.
this.ngZone.runOutsideAngular(() => {
mountFn(this.container.nativeElement)
.then((cleanup) => {
this.destroyFn = cleanup;
})
.catch((err) => {
console.error(
'[DotRemoteModuleWrapper] Failed to mount remote module:',
err
);
});
});
}
}

ngOnDestroy(): void {
try {
this.destroyFn?.();
} catch (err) {
console.error('[DotRemoteModuleWrapper] Failed to unmount remote module:', err);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
import { of, throwError } from 'rxjs';

import { TestBed } from '@angular/core/testing';

import { LoggerService } from '@dotcms/dotcms-js';

import { DotMenuService } from './dot-menu.service';
import { DynamicRouteInitializerService } from './dynamic-route-initializer.service';
import { DynamicRouteService } from './dynamic-route.service';

describe('DynamicRouteInitializerService', () => {
let service: DynamicRouteInitializerService;
let menuService: DotMenuService;
let dynamicRouteService: DynamicRouteService;

const mockMenus = [
{
id: 'menu-1',
name: 'Menu',
tabDescription: '',
tabName: '',
tabOrder: 0,
url: '',
menuItems: [
{
id: 'portlet-1',
label: 'Portlet',
url: '/portlet-1',
ajax: false,
angular: true,
initParams: {
'angular-module': 'remote:http://localhost:4201/remoteEntry.js|p|./Routes'
}
}
]
}
];

beforeEach(() => {
TestBed.configureTestingModule({
providers: [
DynamicRouteInitializerService,
{
provide: DotMenuService,
useValue: {
loadMenu: jest.fn().mockReturnValue(of(mockMenus))
}
},
{
provide: DynamicRouteService,
useValue: {
registerRoutesFromMenuItems: jest.fn().mockReturnValue(1),
getRegisteredRoutes: jest.fn().mockReturnValue(['portlet-1'])
}
},
{
provide: LoggerService,
useValue: {
info: jest.fn(),
error: jest.fn(),
warn: jest.fn()
}
}
]
});

service = TestBed.inject(DynamicRouteInitializerService);
menuService = TestBed.inject(DotMenuService);
dynamicRouteService = TestBed.inject(DynamicRouteService);
});

it('should register routes on first initialization', async () => {
const count = await service.initialize();

expect(menuService.loadMenu).toHaveBeenCalledWith(false);
expect(dynamicRouteService.registerRoutesFromMenuItems).toHaveBeenCalledWith(
mockMenus[0].menuItems
);
expect(count).toBe(1);
expect(service.isInitialized()).toBe(true);
});

it('should be a no-op on repeated calls without force', async () => {
await service.initialize();
jest.clearAllMocks();

const count = await service.initialize();

expect(menuService.loadMenu).not.toHaveBeenCalled();
expect(dynamicRouteService.registerRoutesFromMenuItems).not.toHaveBeenCalled();
expect(count).toBe(0);
});

it('should re-initialize when force=true', async () => {
await service.initialize();
jest.clearAllMocks();

(dynamicRouteService.registerRoutesFromMenuItems as jest.Mock).mockReturnValue(2);
const count = await service.initialize(true);

expect(menuService.loadMenu).toHaveBeenCalledWith(true);
expect(dynamicRouteService.registerRoutesFromMenuItems).toHaveBeenCalled();
expect(count).toBe(2);
});

it('should resolve to 0 on error', async () => {
(menuService.loadMenu as jest.Mock).mockReturnValue(throwError(() => new Error('fail')));

const count = await service.initialize();

expect(count).toBe(0);
expect(service.isInitialized()).toBe(false);
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
import { inject, Injectable } from '@angular/core';

import { filter, take } from 'rxjs/operators';

import { LoggerService } from '@dotcms/dotcms-js';
import { DotMenu } from '@dotcms/dotcms-models';

import { DotMenuService } from './dot-menu.service';
import { DynamicRouteService } from './dynamic-route.service';

/**
* Service that initializes dynamic routes from the menu API.
* Call `initialize()` after user authentication to register any
* dynamic Angular portlets defined in the backend.
*
* @example
* // In a component or service after login
* const count = await this.dynamicRouteInitializer.initialize();
* console.log(`Registered ${count} dynamic routes`);
*/
@Injectable({ providedIn: 'root' })
export class DynamicRouteInitializerService {
private readonly menuService = inject(DotMenuService);
private readonly dynamicRouteService = inject(DynamicRouteService);
private readonly logger = inject(LoggerService);

private initialized = false;

/**
* Initialize dynamic routes from the menu API.
* This should be called once after user authentication.
*
* @param force - Force re-initialization even if already done
* @returns Promise that resolves with the number of routes registered
*/
initialize(force = false): Promise<number> {
if (this.initialized && !force) {
this.logger.info(
this,
'Dynamic routes already initialized. Use force=true to re-initialize.'
);

return Promise.resolve(0);
}

return new Promise((resolve) => {
this.menuService
.loadMenu(force)
.pipe(
filter((menus): menus is DotMenu[] => !!menus),
take(1)
)
.subscribe({
next: (menus) => {
const allMenuItems = menus.flatMap((menu) => menu.menuItems);
const count =
this.dynamicRouteService.registerRoutesFromMenuItems(allMenuItems);

this.initialized = true;
this.logger.info(this, `Initialized ${count} dynamic routes from menu`);
resolve(count);
},
error: (err) => {
this.logger.error(this, 'Failed to initialize dynamic routes:', err);
resolve(0);
}
});
});
}

/**
* Check if dynamic routes have been initialized.
*/
isInitialized(): boolean {
return this.initialized;
}

/**
* Get list of currently registered dynamic routes.
*/
getRegisteredRoutes(): string[] {
return this.dynamicRouteService.getRegisteredRoutes();
}
}
Loading