package com.microsoft.clarity.reactnative import com.facebook.react.bridge.Arguments import com.facebook.react.bridge.ReactApplicationContext import com.facebook.react.bridge.ReactContextBaseJavaModule import com.facebook.react.bridge.ReactMethod import com.facebook.react.modules.core.DeviceEventManagerModule import com.microsoft.clarity.Clarity internal class ClarityEmitter(private val reactContext: ReactApplicationContext) : ReactContextBaseJavaModule(reactContext) { private var listenerCount = 0 private var registeredOnSessionStartedCallback = false override fun getName(): String { return NAME } @ReactMethod fun addListener(eventName: String) { listenerCount += 1 registerOnSessionStartedCallback() } @ReactMethod fun removeListeners(count: Int) { listenerCount -= count } private fun registerOnSessionStartedCallback() { // `setOnSessionStartedCallback` should be called: // - once to maintain the same callback. // - only when there are listeners so that they can receive the first invocation from the SDK. if (registeredOnSessionStartedCallback) return registeredOnSessionStartedCallback = Clarity.setOnSessionStartedCallback { sessionId -> if (listenerCount <= 0) return@setOnSessionStartedCallback val params = Arguments.createMap().apply { putString(CLARITY_SESSION_ID_PARAMETER, sessionId) } reactContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter::class.java) .emit(CLARITY_EVENT_SESSION_STARTED, params) } } companion object { const val NAME = "ClarityEmitter" const val CLARITY_EVENT_SESSION_STARTED = "sessionStarted" const val CLARITY_SESSION_ID_PARAMETER = "sessionId" } }