-
Notifications
You must be signed in to change notification settings - Fork 480
Issue 34526 plugin angular portlets #34527
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
Changes from all commits
Commits
Show all changes
14 commits
Select commit
Hold shift + click to select a range
2058eae
feat(portlet): this introduces the dynamic-route-service that reads t…
wezell f112022
feat(portlet): this introduces the dynamic-route-service that reads t…
wezell abf69fc
feat(portlet): this updates the Angular version we use in order to av…
wezell 4f3b40a
Update core-web/apps/dotcms-ui/src/app/api/services/dynamic-route.ser…
wezell 18a421a
feat(portlet): fixing github feedback
wezell 0832c70
Merge remote-tracking branch 'origin/issue-34526-allow-ng-portlets' i…
wezell 1cc30d2
feat(portlet): more ng version bumps
wezell 88b3267
feat(portlet): prettified
wezell 53bc4fd
Merge branch 'main' into issue-34526-allow-ng-portlets
wezell c52b0b2
feat(portlet): fixing front end tests
wezell 4a721a5
Merge remote-tracking branch 'origin/issue-34526-allow-ng-portlets' i…
wezell 49c1e75
Merge remote-tracking branch 'origin/main' into issue-34526-allow-ng-…
wezell 793031f
feat(portlet): fixing front end tests
wezell 5cd0be9
Merge branch 'main' into issue-34526-allow-ng-portlets
wezell File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
99 changes: 99 additions & 0 deletions
99
core-web/apps/dotcms-ui/src/app/api/services/dot-remote-module-wrapper.component.spec.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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(); | ||
| })); | ||
| }); |
64 changes: 64 additions & 0 deletions
64
core-web/apps/dotcms-ui/src/app/api/services/dot-remote-module-wrapper.component.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 | ||
wezell marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| // 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); | ||
| } | ||
| } | ||
| } | ||
114 changes: 114 additions & 0 deletions
114
core-web/apps/dotcms-ui/src/app/api/services/dynamic-route-initializer.service.spec.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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); | ||
| }); | ||
| }); |
84 changes: 84 additions & 0 deletions
84
core-web/apps/dotcms-ui/src/app/api/services/dynamic-route-initializer.service.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,84 @@ | ||
| import { inject, Injectable } from '@angular/core'; | ||
wezell marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| 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.' | ||
wezell marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| ); | ||
|
|
||
| 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(); | ||
| } | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.