diff --git a/projects/igniteui-angular-elements/src/lib/icon.broadcast.service.ts b/projects/igniteui-angular-elements/src/lib/icon.broadcast.service.ts index 493096a9fa3..0ae7f09a676 100644 --- a/projects/igniteui-angular-elements/src/lib/icon.broadcast.service.ts +++ b/projects/igniteui-angular-elements/src/lib/icon.broadcast.service.ts @@ -7,49 +7,68 @@ import { IconMeta } from '../../../igniteui-angular/src/lib/icon/public_api'; export interface SvgIcon { svg: string; title?: string; - } +} - export type Collection = Map; +export type Collection = Map; - export enum ActionType { +export enum ActionType { SyncState = 0, RegisterIcon = 1, UpdateIconReference = 2, - } +} - export interface BroadcastIconsChangeMessage { +export interface BroadcastIconsChangeMessage { actionType: ActionType; collections?: Collection>; references?: Collection>; - } +} /** @hidden @internal **/ @Injectable() export class IgxIconBroadcastService { - private iconBroadcastChannel: BroadcastChannel; + private iconBroadcastChannel: BroadcastChannel | null; + constructor( protected _iconService: IgxIconService, @Optional() private _platformUtil: PlatformUtil ) { if (this._platformUtil?.isBrowser) { - // open broadcast channel for sync with wc icon service. - this.iconBroadcastChannel = new BroadcastChannel("ignite-ui-icon-channel"); - this.iconBroadcastChannel.onmessage = (event) => { - const message = event.data as BroadcastIconsChangeMessage; - if (message.actionType === ActionType.SyncState || - message.actionType === ActionType.RegisterIcon) { - this.updateIconsFromCollection(message.collections); - } - - if (message.actionType === ActionType.SyncState || - message.actionType === ActionType.UpdateIconReference) { - this.updateRefsFromCollection(message.references); - } - }; - // send message to sync state + this.create(); + + globalThis.addEventListener('pageshow', () => this.create()) + globalThis.addEventListener('pagehide', () => this.dispose()) + } + } + + public handleEvent({ data }: MessageEvent) { + const { actionType, collections, references } = data; + + if (actionType === ActionType.SyncState || ActionType.RegisterIcon) { + this.updateIconsFromCollection(collections); + } + + if (actionType === ActionType.SyncState || ActionType.UpdateIconReference) { + this.updateRefsFromCollection(references); + } + } + + private create() { + if (!this.iconBroadcastChannel) { + this.iconBroadcastChannel = new BroadcastChannel('ignite-ui-icon-channel'); + this.iconBroadcastChannel.addEventListener('message', this); + + // sync state this.iconBroadcastChannel.postMessage({ actionType: ActionType.SyncState - }); + }) + } + } + + private dispose() { + if (this.iconBroadcastChannel) { + this.iconBroadcastChannel.removeEventListener('message', this); + this.iconBroadcastChannel.close(); + this.iconBroadcastChannel = null; } }