import { reportError } from '@/events'; import { hostEmitter } from '@jolibox/common'; import { HostEventParamsMap } from '@jolibox/types'; import { APIError } from '@jolibox/common'; /** * Defines the supported custom event names. * @public */ export type CustomEventType = 'onI18nChanged' | 'onBackPress'; const supportedEvents: CustomEventType[] = ['onI18nChanged', 'onBackPress']; /** * @public * Registers a listener for a supported custom event. * The callback will receive parameters specific to the event, as defined in {@link HostEventParamsMap}. * @template T - The type of the event name, constrained to {@link CustomEventType}. * @param event - The name of the event to listen for. * @param callback - The callback function to execute when the event is triggered. Its parameters depend on the event type. */ export const onCustomEvent = (event: T, callback: HostEventParamsMap[T]): void => { if (!supportedEvents.includes(event)) { reportError(new APIError(`[onCustomEvent] Unsupported event: ${event}`, 2000)); return; // It's good practice to return after reporting an error if proceeding is problematic } hostEmitter.on(event, callback); }; /** * @public * Unregisters a listener for a custom event. * @template T - The type of the event name, constrained to {@link CustomEventType}. * @param event - The name of the event. * @param callback - The specific callback to remove. If not provided, all listeners for the event might be removed (depending on hostEmitter implementation, though typically a specific callback is required by EventEmitter.off). */ export const offCustomEvent = ( event: T, callback: HostEventParamsMap[T] ): void => { if (!supportedEvents.includes(event)) { reportError(new APIError(`[offCustomEvent] Unsupported event: ${event}`, 2000)); return; } hostEmitter.off(event, callback); }; /** * @public * Registers a one-time listener for a custom event. The listener is automatically removed after being invoked once. * @template T - The type of the event name, constrained to {@link CustomEventType}. * @param event - The name of the event to listen for. * @param callback - The callback function to execute. Its parameters depend on the event type from {@link HostEventParamsMap}. */ export const onceCustomEvent = ( event: T, callback: HostEventParamsMap[T] ): void => { if (!supportedEvents.includes(event)) { reportError(new APIError(`[onceCustomEvent] Unsupported event: ${event}`, 2000)); return; } hostEmitter.once(event, callback); };