Skip to content

Commit

Permalink
refactor(elements): Close icon service broadcast channel on pagehide (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
rkaraivanov authored Oct 4, 2024
1 parent a34e44c commit e428829
Showing 1 changed file with 42 additions and 23 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -7,49 +7,68 @@ import { IconMeta } from '../../../igniteui-angular/src/lib/icon/public_api';
export interface SvgIcon {
svg: string;
title?: string;
}
}

export type Collection<T, U> = Map<T, U>;
export type Collection<T, U> = Map<T, U>;

export enum ActionType {
export enum ActionType {
SyncState = 0,
RegisterIcon = 1,
UpdateIconReference = 2,
}
}

export interface BroadcastIconsChangeMessage {
export interface BroadcastIconsChangeMessage {
actionType: ActionType;
collections?: Collection<string, Map<string, SvgIcon>>;
references?: Collection<string, Map<string, IconMeta>>;
}
}

/** @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<BroadcastIconsChangeMessage>) {
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;
}
}

Expand Down

0 comments on commit e428829

Please sign in to comment.