/* eslint-disable @typescript-eslint/naming-convention */ import { GraniteEventDefinition } from '@granite-js/react-native'; import { INTERNAL__appBridgeHandler } from './appBridge'; import { MiniAppModule } from '../../../natives'; export interface AppBridgeCallbackResult { name: string; params?: any; } export class AppBridgeCallbackEvent extends GraniteEventDefinition { private static INTERNAL__appBridgeSubscription?: () => void; name = 'appBridgeCallbackEvent' as const; constructor() { super(); this.registerAppBridgeCallbackEventListener(); } remove() {} listener() {} private registerAppBridgeCallbackEventListener() { if (AppBridgeCallbackEvent.INTERNAL__appBridgeSubscription != null) { return; } const subscription = MiniAppModule.onSendEvent(({ eventName, body }) => { if (eventName === 'appBridgeCallback') { this.ensureInvokeAppBridgeCallback(body as AppBridgeCallbackResult); } }); AppBridgeCallbackEvent.INTERNAL__appBridgeSubscription = () => subscription.remove(); } private ensureInvokeAppBridgeCallback(result: AppBridgeCallbackResult) { if (typeof result === 'object' && typeof result.name === 'string') { INTERNAL__appBridgeHandler.invokeAppBridgeCallback(result.name, result.params); } else { console.warn('Invalid app bridge callback result:', result); } } }