Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 20 additions & 3 deletions example/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,18 @@ import TraceScreen from './screens/TraceScreen';
import style from './screens/styles';
import { navigationRef } from './NavigationRoot';
import { DdRumReactNavigationTracking, NavigationTrackingOptions, ParamsTrackingPredicate, ViewNamePredicate, ViewTrackingPredicate } from '@datadog/mobile-react-navigation';
import { DatadogProvider, TrackingConsent, DdFlags } from '@datadog/mobile-react-native'
import { DatadogProvider, TrackingConsent, DdFlags, DdLogs, DdSdkReactNative } from '@datadog/mobile-react-native'
import { DatadogOpenFeatureProvider } from '@datadog/mobile-react-native-openfeature';
import {
ImagePrivacyLevel,
SessionReplay,
TextAndInputPrivacyLevel,
TouchPrivacyLevel,
} from '@datadog/mobile-react-native-session-replay';
import { OpenFeature, OpenFeatureProvider } from '@openfeature/react-sdk';
import { Route } from "@react-navigation/native";
import { NestedNavigator } from './screens/NestedNavigator/NestedNavigator';
import { getDatadogConfig, onDatadogInitialization } from './ddUtils';
import { getDatadogConfig } from './ddUtils';

const Tab = createBottomTabNavigator();

Expand Down Expand Up @@ -69,7 +75,18 @@ const configuration = getDatadogConfig(TrackingConsent.GRANTED)
// const configuration = new DatadogProviderConfiguration("fake_value", "fake_value");

const handleDatadogInitialization = async () => {
onDatadogInitialization();
DdLogs.info('The RN Sdk was properly initialized')
DdSdkReactNative.setUserInfo({id: "1337", name: "Xavier", email: "xg@example.com", extraInfo: { type: "premium" } })
DdSdkReactNative.addAttributes({campaign: "ad-network"})

// Enable Session Replay.
await SessionReplay.enable({
replaySampleRate: 100,
textAndInputPrivacyLevel: TextAndInputPrivacyLevel.MASK_SENSITIVE_INPUTS,
imagePrivacyLevel: ImagePrivacyLevel.MASK_NONE,
touchPrivacyLevel: TouchPrivacyLevel.SHOW,
enableHeatmaps: true,
});

// Enable Datadog Flags feature.
await DdFlags.enable();
Expand Down
6 changes: 0 additions & 6 deletions example/src/ddUtils.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -57,12 +57,6 @@ export function getDatadogConfig(trackingConsent: TrackingConsent) {
return config
}

export function onDatadogInitialization() {
DdLogs.info('The RN Sdk was properly initialized')
DdSdkReactNative.setUserInfo({id: "1337", name: "Xavier", email: "xg@example.com", extraInfo: { type: "premium" } })
DdSdkReactNative.addAttributes({campaign: "ad-network"})
}

// Legacy SDK Setup
export function initializeDatadog(trackingConsent: TrackingConsent) {

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,10 @@ import java.util.Locale
* The entry point to use Datadog's RUM feature.
*/
@Suppress("TooManyFunctions")
class DdRumImplementation(private val datadog: DatadogWrapper = DatadogSDKWrapper()) {
class DdRumImplementation internal constructor(
private val datadog: DatadogWrapper = DatadogSDKWrapper(),
private val heatmapActionHandler: HeatmapActionHandler = HeatmapActionHandler()
) {
/**
* Start tracking a RUM View.
* @param key The view unique key identifier.
Expand Down Expand Up @@ -120,11 +123,10 @@ class DdRumImplementation(private val datadog: DatadogWrapper = DatadogSDKWrappe
* @param type The action type (tap, scroll, swipe, click, custom).
* @param name The action name.
* @param touch The native touch data for tap actions, or null for other action types.
* Currently unused on Android; reserved for heatmap support.
* @param context The additional context to send.
* @param timestampMs The timestamp when the action occurred (in milliseconds). If not provided, current timestamp will be used.
*/
@Suppress("LongParameterList", "UnusedParameter")
@Suppress("LongParameterList")
fun addAction(
type: String,
name: String,
Expand All @@ -136,12 +138,28 @@ class DdRumImplementation(private val datadog: DatadogWrapper = DatadogSDKWrappe
val attributes = context.toHashMap().toMutableMap().apply {
put(RumAttributes.INTERNAL_TIMESTAMP, timestampMs.toLong())
}

val eligibleAction = heatmapActionHandler.resolveEligibility(datadog, type, name, touch)
if (eligibleAction == null) {
addActionWithoutHeatmap(type, name, attributes)
promise.resolve(null)
return
}

// Resolve before dispatching heatmap work (iOS parity).
promise.resolve(null)

heatmapActionHandler.attachHeatmapData(eligibleAction, name, attributes) {
addActionWithoutHeatmap(type, name, attributes)
}
}

private fun addActionWithoutHeatmap(type: String, name: String, attributes: Map<String, Any?>) {
datadog.getRumMonitor().addAction(
type = type.asRumActionType(),
name = name,
attributes = attributes
)
promise.resolve(null)
}

/**
Expand Down Expand Up @@ -460,6 +478,7 @@ class DdRumImplementation(private val datadog: DatadogWrapper = DatadogSDKWrappe
}

// endregion

@Suppress("UndocumentedPublicClass")
companion object {
private const val MISSING_RESOURCE_SIZE = -1L
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
/*
* Unless explicitly stated otherwise all files in this repository are licensed under the Apache License Version 2.0.
* This product includes software developed at Datadog (https://www.datadoghq.com/).
* Copyright 2016-Present Datadog, Inc.
*/

package com.datadog.reactnative

import android.os.Handler
import android.os.Looper
import com.datadog.android.api.InternalLogger
import com.datadog.android.rum.RumActionType
import com.datadog.android.rum._RumInternalProxy
import com.facebook.react.bridge.ReadableMap

/**
* Decides whether an `addAction` call is eligible for heatmap tracking and, if so, resolves and
* attaches the heatmap data via [HeatmapTouchResolver]. Split into two steps so the caller can
* resolve its own promise between them, before the heatmap work dispatches.
*/
class HeatmapActionHandler internal constructor(
private val heatmapTouchResolver: HeatmapTouchResolver = HeatmapTouchResolver(),
private val mainThreadExecutor: (() -> Unit) -> Unit = { action ->
Handler(Looper.getMainLooper()).post(action)
}
) {

internal data class EligibleAction(
val internalProxy: _RumInternalProxy,
val viewUrl: String,
val reactTag: Int,
val positionX: Long,
val positionY: Long
)

internal fun resolveEligibility(
datadog: DatadogWrapper,
type: String,
name: String,
touch: ReadableMap?
): EligibleAction? {
if (!heatmapsEnabled || touch == null || !type.equals("tap", ignoreCase = true)) {
return null
}

val internalProxy = datadog.getRumMonitor()._getInternal()
// Read now — the view can transition asynchronously right after a tap.
val viewUrl = internalProxy?.getCurrentViewUrl()
val touchFields = touch.toTouchFieldsOrNull(name)

return if (internalProxy != null && viewUrl != null && touchFields != null) {
val (reactTag, positionX, positionY) = touchFields
EligibleAction(internalProxy, viewUrl, reactTag, positionX, positionY)
} else {
null
}
}

internal fun attachHeatmapData(
eligibleAction: EligibleAction,
name: String,
attributes: Map<String, Any?>,
fallback: () -> Unit
) {
mainThreadExecutor {
val heatmapData = heatmapTouchResolver.resolveHeatmapActionData(
eligibleAction.reactTag,
eligibleAction.positionX,
eligibleAction.positionY,
eligibleAction.viewUrl
)
if (heatmapData != null) {
eligibleAction.internalProxy.addActionWithHeatmap(
type = RumActionType.TAP,
name = name,
crossPlatformHeatmapActionData = heatmapData,
attributes = attributes
)
} else {
fallback()
}
}
}

// Missing fields are not warned on: `actionContext` is an optional addAction parameter, and
// a caller intentionally tracking a TAP action without real touch coordinates is valid usage.
private fun ReadableMap.toTouchFieldsOrNull(actionName: String): Triple<Int, Long, Long>? {
if (!hasKey("reactTag") || !hasKey("x") || !hasKey("y")) return null
return runCatching {
Triple(getInt("reactTag"), getDouble("x").toLong(), getDouble("y").toLong())
}.onFailure {
InternalLogger.UNBOUND.log(
InternalLogger.Level.WARN,
InternalLogger.Target.USER,
{
"addAction(\"$actionName\"): heatmap tracking requires actionContext's " +
"nativeEvent.target/locationX/locationY to be numbers, as produced by a " +
"standard onPress GestureResponderEvent. The value passed for this " +
"action didn't match that shape, so heatmap tracking was skipped for it " +
"— this is expected if actionContext came from a non-standard event " +
"source (e.g. a different gesture library)."
},
throwable = it,
onlyOnce = true
)
}.getOrNull()
}

@Suppress("UndocumentedPublicClass")
companion object {
/**
* Whether heatmap data should be attached to TAP actions. Set by
* [com.datadog.reactnative.sessionreplay.DdSessionReplayImplementation.enable].
*/
@Volatile
var heatmapsEnabled: Boolean = false
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
/*
* Unless explicitly stated otherwise all files in this repository are licensed under the Apache License Version 2.0.
* This product includes software developed at Datadog (https://www.datadoghq.com/).
* Copyright 2016-Present Datadog, Inc.
*/

package com.datadog.reactnative

import android.content.res.Resources
import android.view.View
import android.view.ViewGroup
import com.datadog.android.heatmaps.CrossPlatformHeatmapActionData

/**
* Resolves a React Native touch into [CrossPlatformHeatmapActionData] by walking the view
* hierarchy to the nearest clickable-and-visible ancestor — matching Session Replay's own
* `HeatmapIdentifierResolver` rule — and building its element path using the same convention, so
* the resulting hash matches the `permanentId` SR assigned to that view's wireframe.
*/
internal class HeatmapTouchResolver(
private val viewResolver: (Int) -> View? = { null },
private val telemetry: DdTelemetry = DdTelemetry()
) {

/** Returns null if [reactTag] doesn't resolve to a valid tap target. */
fun resolveHeatmapActionData(
reactTag: Int,
positionX: Long,
positionY: Long,
viewUrl: String
): CrossPlatformHeatmapActionData? = runCatching {
val view = viewResolver(reactTag)?.let { clickableVisibleAncestorOf(it) }
val elementPath = view?.let { elementPathFromRootTo(it) }

if (view != null && !elementPath.isNullOrEmpty()) {
val density = view.resources?.displayMetrics?.density ?: 1f
val targetWidth = (view.width / density).toLong().takeIf { it > 0 }
val targetHeight = (view.height / density).toLong().takeIf { it > 0 }

CrossPlatformHeatmapActionData(
elementPath = elementPath,
viewUrl = viewUrl,
positionX = positionX,
positionY = positionY,
targetWidth = targetWidth,
targetHeight = targetHeight
)
} else {
null
}
}.onFailure {
telemetry.telemetryError("Failed to resolve heatmap action data", it)
}.getOrNull()

// region Private helpers

private fun clickableVisibleAncestorOf(view: View): View? {
var current: View? = view
while (current != null) {
if (current.isClickable && current.visibility == View.VISIBLE) {
return current
}
current = current.parent as? View
}
return null
}

private fun elementPathFromRootTo(view: View): List<String> {
val path = mutableListOf<String>()
var current: View? = view
while (current != null) {
val parent = current.parent as? ViewGroup
val typeIndex = if (parent != null) computeTypeIndex(current, parent) else 0
path.add(pathComponentFor(current, typeIndex))
current = parent
}
path.reverse()
return path
}

private fun computeTypeIndex(view: View, parent: ViewGroup): Int {
val cls = view.javaClass
var index = 0
for (i in 0 until parent.childCount) {
val child = parent.getChildAt(i) ?: continue
if (child === view) break
if (child.javaClass === cls) index++
}
return index
}

private fun pathComponentFor(view: View, typeIndex: Int): String {
val viewId = view.id
if (viewId != View.NO_ID) {
try {
@Suppress("UnsafeThirdPartyFunctionCall")
val name = view.resources?.getResourceName(viewId)
if (!name.isNullOrEmpty()) {
return "$name#$typeIndex"
}
} catch (_: Resources.NotFoundException) {
}
}
return "cls:${view.javaClass.name}#$typeIndex"
}

// endregion
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ import com.facebook.react.bridge.ReactApplicationContext
import com.facebook.react.bridge.ReactMethod
import com.facebook.react.bridge.ReadableArray
import com.facebook.react.bridge.ReadableMap
import com.facebook.react.uimanager.UIManagerHelper
import com.facebook.react.uimanager.common.ViewUtil

/**
* The entry point to use Datadog's RUM feature.
Expand All @@ -22,7 +24,23 @@ class DdRum(
datadogWrapper: DatadogWrapper = DatadogSDKWrapper()
) : NativeDdRumSpec(reactContext) {

private val implementation = DdRumImplementation(datadog = datadogWrapper)
private val telemetry = DdTelemetry()

private val implementation = DdRumImplementation(
datadog = datadogWrapper,
heatmapActionHandler = HeatmapActionHandler(
heatmapTouchResolver = HeatmapTouchResolver(viewResolver = { reactTag ->
try {
val uiManagerType = ViewUtil.getUIManagerType(reactTag)
UIManagerHelper.getUIManager(reactApplicationContext, uiManagerType)
?.resolveView(reactTag)
} catch (e: Exception) {
telemetry.telemetryError("Failed to resolve view for heatmap tracking", e)
null
}
})
)
)

override fun getName(): String = DdRumImplementation.NAME

Expand Down Expand Up @@ -105,7 +123,6 @@ class DdRum(
* @param type The action type (tap, scroll, swipe, click, custom).
* @param name The action name.
* @param touch The native touch data for tap actions, or null for other action types.
* Currently unused on Android; reserved for heatmap support.
* @param context The additional context to send.
* @param timestampMs The timestamp when the action occurred (in milliseconds).
* If not provided, current timestamp will be used.
Expand Down
Loading