package com.microsoft.clarity.reactnative import android.os.Handler import android.os.Looper import com.facebook.react.bridge.* import com.microsoft.clarity.Clarity import com.microsoft.clarity.ClarityConfig import com.microsoft.clarity.models.ApplicationFramework import com.microsoft.clarity.models.LogLevel class ClarityModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaModule(reactContext) { override fun getName(): String { return NAME } @ReactMethod fun initialize( projectId: String, userId: String?, logLevel: String, promise: Promise ) { val config = ClarityConfig( projectId, userId, LogLevel.valueOf(logLevel), ApplicationFramework.ReactNative ) // Run on the main thread as recommended by the native Clarity SDK. Handler(Looper.getMainLooper()).post { promise.resolve(Clarity.initialize(reactApplicationContext.currentActivity, config)) } } @ReactMethod fun pause(promise: Promise) { // Cannot resolve void Clarity.pause() promise.resolve(Clarity.isPaused()) } @ReactMethod fun resume(promise: Promise) { // Cannot resolve void Clarity.resume() promise.resolve(!Clarity.isPaused()) } @ReactMethod fun isPaused(promise: Promise) { promise.resolve(Clarity.isPaused()) } @ReactMethod fun startNewSession(callback: Callback) { Clarity.startNewSession { callback.invoke(it) } } @ReactMethod fun setCustomUserId(customUserId: String, promise: Promise) { promise.resolve(Clarity.setCustomUserId(customUserId)) } @ReactMethod fun setCustomSessionId(customSessionId: String, promise: Promise) { promise.resolve(Clarity.setCustomSessionId(customSessionId)) } @ReactMethod fun getCurrentSessionId(promise: Promise) { promise.resolve(Clarity.getCurrentSessionId()) } @ReactMethod fun setCustomTag(key: String?, value: String?, promise: Promise) { promise.resolve(Clarity.setCustomTag(key, value)) } @ReactMethod fun setCustomTags(key: String?, values: ReadableArray?, promise: Promise) { val tagValues = values?.let { readableArrayToList(it) } ?: emptyList() promise.resolve(Clarity.setCustomTag(key, *tagValues.toTypedArray())) } @ReactMethod fun sendCustomEvent(value: String, promise: Promise) { promise.resolve(Clarity.sendCustomEvent(value)) } @ReactMethod fun setCurrentScreenName(screenName: String?, promise: Promise) { promise.resolve(Clarity.setCurrentScreenName(screenName)) } @ReactMethod fun getCurrentSessionUrl(promise: Promise) { promise.resolve(Clarity.getCurrentSessionUrl()) } @ReactMethod fun consent(adsStorage: Boolean, analyticsStorage: Boolean, promise: Promise) { promise.resolve(Clarity.consent(adsStorage, analyticsStorage)) } private fun readableArrayToList(arr: ReadableArray): List { val ret = mutableListOf() for (i in 0 until arr.size()) { if (!arr.isNull(i)) { arr.getString(i)?.let { ret.add(it) } } } return ret } companion object { const val NAME = "Clarity" } }