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
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@
}

# CustomStyleSpan is looked up by name via Class.forName() and its getFontFamily() method is
# invoked reflectively (LegacyTextViewUtils) to resolve font family for RUM Session Replay.
# invoked reflectively (LegacyTextViewUtils and PreparedLayoutTextViewMapper) to resolve font
# family for RUM Session Replay.
# The class name and method must both be preserved for this to keep working.
-keep class com.facebook.react.views.text.internal.span.CustomStyleSpan {
public java.lang.String getFontFamily();
Expand Down Expand Up @@ -43,3 +44,13 @@
*** computedBorderRadius;
*** backgroundColor;
}

# Prepared text is optional on older RN versions; its public accessors are read reflectively.
-keep class com.facebook.react.views.text.PreparedLayoutTextView {
public *** getPreparedLayout();
public java.lang.CharSequence getText();
}
-keep class com.facebook.react.views.text.PreparedLayout {
public android.text.Layout getLayout();
public float getVerticalOffset();
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,12 @@

package com.datadog.reactnative.sessionreplay

import android.view.ViewGroup
import com.datadog.android.sessionreplay.ExtensionSupport
import com.datadog.android.sessionreplay.MapperTypeWrapper
import com.datadog.android.sessionreplay.recorder.OptionSelectorDetector
import com.datadog.android.sessionreplay.utils.DrawableToColorMapper
import com.datadog.reactnative.sessionreplay.mappers.PreparedLayoutTextViewMapper
import com.datadog.reactnative.sessionreplay.mappers.ReactEditTextMapper
import com.datadog.reactnative.sessionreplay.mappers.ReactNativeImageViewMapper
import com.datadog.reactnative.sessionreplay.mappers.ReactTextMapper
Expand All @@ -24,24 +26,28 @@ import com.facebook.react.views.text.ReactTextView
import com.facebook.react.views.textinput.ReactEditText
import com.facebook.react.views.view.ReactViewGroup


internal class ReactNativeSessionReplayExtensionSupport(
private val textViewUtils: TextViewUtils,
private val internalCallback: ReactNativeInternalCallback
private val internalCallback: ReactNativeInternalCallback,
private val preparedTextViewClass: Class<out ViewGroup>? = PreparedLayoutTextViewMapper.resolveViewClass()
) : ExtensionSupport {
override fun name(): String {
return ReactNativeSessionReplayExtensionSupport::class.java.simpleName
}

override fun getCustomViewMappers(): List<MapperTypeWrapper<*>> {
return listOf(
val mappers = mutableListOf<MapperTypeWrapper<*>>(
MapperTypeWrapper(ReactImageView::class.java, ReactNativeImageViewMapper()),
MapperTypeWrapper(DdPrivacyView::class.java, SvgViewMapper(internalCallback)),
MapperTypeWrapper(ReactViewGroup::class.java, ReactViewGroupMapper()),
MapperTypeWrapper(ReactTextView::class.java, ReactTextMapper(textViewUtils)),
MapperTypeWrapper(ReactEditText::class.java, ReactEditTextMapper(textViewUtils)),
MapperTypeWrapper(ReactModalHostView::class.java, ReactViewModalMapper()),
MapperTypeWrapper(ReactModalHostView::class.java, ReactViewModalMapper())
)
preparedTextViewClass?.let {
mappers.add(MapperTypeWrapper(it, PreparedLayoutTextViewMapper()))
}
return mappers
}

override fun getOptionSelectorDetectors(): List<OptionSelectorDetector> {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,208 @@
/*
* 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.sessionreplay.mappers

import ReactViewBackgroundDrawableUtils
import android.graphics.Typeface
import android.text.Layout
import android.text.Spanned
import android.text.style.AbsoluteSizeSpan
import android.text.style.ForegroundColorSpan
import android.view.View
import android.view.ViewGroup
import com.datadog.android.api.InternalLogger
import com.datadog.android.sessionreplay.TextAndInputPrivacy
import com.datadog.android.sessionreplay.internal.recorder.obfuscator.StringObfuscator
import com.datadog.android.sessionreplay.model.MobileSegment
import com.datadog.android.sessionreplay.recorder.MappingContext
import com.datadog.android.sessionreplay.recorder.mapper.TraverseAllChildrenMapper
import com.datadog.android.sessionreplay.utils.AsyncJobStatusCallback
import com.datadog.reactnative.sessionreplay.utils.DrawableUtils
import com.datadog.reactnative.sessionreplay.utils.formatAsRgba
import java.lang.reflect.Method
import java.util.Locale

/** Maps the ViewGroup-based text implementation introduced in RN 0.89. */
internal class PreparedLayoutTextViewMapper(
private val layoutReader: (View, InternalLogger) -> PreparedTextLayout? = PreparedTextLayoutReader()::read,
drawableUtils: DrawableUtils = ReactViewBackgroundDrawableUtils(),
private val obfuscator: StringObfuscator = StringObfuscator.getStringObfuscator()
) : DefaultMapper<ViewGroup>(drawableUtils), TraverseAllChildrenMapper<ViewGroup> {

private val fontFamilyMethod: Method? by lazy {
try {
Class.forName(
"com.facebook.react.views.text.internal.span.CustomStyleSpan",
false,
PreparedLayoutTextViewMapper::class.java.classLoader
).getMethod("getFontFamily")
} catch (_: ReflectiveOperationException) {
null
} catch (_: LinkageError) {
null
} catch (_: SecurityException) {
null
}
}

override fun map(
view: ViewGroup,
mappingContext: MappingContext,
asyncJobStatusCallback: AsyncJobStatusCallback,
internalLogger: InternalLogger
): List<MobileSegment.Wireframe> {
val background = super.map(view, mappingContext, asyncJobStatusCallback, internalLogger)
.first() as MobileSegment.Wireframe.ShapeWireframe
val prepared = layoutReader(view, internalLogger) ?: return listOf(background)
val density = mappingContext.systemInformation.screenDensity.coerceAtLeast(1f)
return listOf(
MobileSegment.Wireframe.TextWireframe(
id = background.id,
x = background.x,
y = background.y,
width = background.width,
height = background.height,
shapeStyle = background.shapeStyle ?: MobileSegment.ShapeStyle(
backgroundColor = "#00000000",
opacity = view.alpha,
cornerRadius = 0L
),
border = background.border,
// Layout text includes ellipsis; source text is retained only for style spans.
text = capturedText(prepared.layout.text, mappingContext),
textStyle = textStyle(prepared, density),
textPosition = textPosition(view, prepared, density)
)
)
}

private fun capturedText(text: CharSequence, context: MappingContext): String {
val original = text.toString()
return when (context.textAndInputPrivacy) {
TextAndInputPrivacy.MASK_ALL -> if (context.hasOptionSelectorParent) {
INPUT_MASK
} else {
obfuscator.obfuscate(original)
}
TextAndInputPrivacy.MASK_ALL_INPUTS -> if (context.hasOptionSelectorParent) {
INPUT_MASK
} else {
original
}
TextAndInputPrivacy.MASK_SENSITIVE_INPUTS -> original
}
}

private fun textStyle(prepared: PreparedTextLayout, density: Float): MobileSegment.TextStyle {
val paint = prepared.layout.paint
val spanColor = (prepared.sourceText as? Spanned)
?.getSpans(0, prepared.sourceText.length, ForegroundColorSpan::class.java)
?.firstOrNull()?.foregroundColor
val family = fontFamilyFromSpans(prepared.sourceText) ?: when (paint.typeface) {
Typeface.MONOSPACE -> MONOSPACE_FAMILY_NAME
Typeface.SERIF -> SERIF_FAMILY_NAME
else -> SANS_SERIF_FAMILY_NAME
}
return MobileSegment.TextStyle(
family = when (family.lowercase(Locale.US)) {
MONOSPACE_FAMILY_NAME -> MONOSPACE_FAMILY_NAME
SERIF_FAMILY_NAME -> SERIF_FAMILY_NAME
else -> SANS_SERIF_FAMILY_NAME
},
size = fontSize(prepared, density),
color = formatAsRgba(spanColor ?: paint.color),
truncationMode = truncationMode(prepared.layout)
)
}

private fun fontSize(prepared: PreparedTextLayout, density: Float): Long {
val span = (prepared.sourceText as? Spanned)
?.getSpans(0, prepared.sourceText.length, AbsoluteSizeSpan::class.java)
?.firstOrNull()
return span?.let {
if (it.dip) it.size.toLong() else (it.size / density).toLong()
} ?: (prepared.layout.paint.textSize / density).toLong()
}

private fun fontFamilyFromSpans(text: CharSequence): String? {
val spanned = text as? Spanned ?: return null
val method = fontFamilyMethod ?: return null
val span = spanned.getSpans(0, spanned.length, method.declaringClass)
?.firstOrNull() ?: return null
return try {
method.invoke(span) as? String
} catch (_: ReflectiveOperationException) {
null
} catch (_: SecurityException) {
null
}
}

private fun textPosition(
view: View,
prepared: PreparedTextLayout,
density: Float
): MobileSegment.TextPosition {
val layout = prepared.layout
val rtl = layout.lineCount > 0 && layout.getParagraphDirection(0) < 0
val horizontal = when (layout.alignment) {
Layout.Alignment.ALIGN_CENTER -> MobileSegment.Horizontal.CENTER
Layout.Alignment.ALIGN_OPPOSITE -> if (rtl) MobileSegment.Horizontal.LEFT else MobileSegment.Horizontal.RIGHT
else -> if (rtl) MobileSegment.Horizontal.RIGHT else MobileSegment.Horizontal.LEFT
}
return MobileSegment.TextPosition(
padding = MobileSegment.Padding(
top = ((view.paddingTop + prepared.verticalOffset) / density).toLong(),
bottom = (view.paddingBottom / density).toLong(),
left = (view.paddingLeft / density).toLong(),
right = (view.paddingRight / density).toLong()
),
alignment = MobileSegment.Alignment(horizontal, MobileSegment.Vertical.TOP)
)
}

private fun truncationMode(layout: Layout): MobileSegment.TruncationMode? {
for (line in 0 until layout.lineCount) {
val count = layout.getEllipsisCount(line)
if (count > 0) {
val start = layout.getEllipsisStart(line)
return when {
line == 0 && start == 0 -> MobileSegment.TruncationMode.HEAD
start + count < layout.getLineEnd(line) - layout.getLineStart(line) -> MobileSegment.TruncationMode.MIDDLE
else -> MobileSegment.TruncationMode.TAIL
}
}
}
return null
}

internal companion object {
private const val INPUT_MASK: String = "***"
private const val MONOSPACE_FAMILY_NAME: String = "monospace"
private const val SERIF_FAMILY_NAME: String = "serif"
private const val SANS_SERIF_FAMILY_NAME: String = "roboto, sans-serif"

/** Missing classes are expected on RN versions before prepared text was introduced. */
fun resolveViewClass(): Class<out ViewGroup>? {
return try {
Class.forName(
"com.facebook.react.views.text.PreparedLayoutTextView",
false,
PreparedLayoutTextViewMapper::class.java.classLoader
).asSubclass(ViewGroup::class.java)
} catch (_: ClassNotFoundException) {
null
} catch (_: LinkageError) {
null
} catch (_: ClassCastException) {
null
} catch (_: SecurityException) {
null
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
/*
* 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.sessionreplay.mappers

import android.text.Layout
import android.view.View
import com.datadog.android.api.InternalLogger
import java.lang.reflect.Method

/** A snapshot of React Native's prepared text layout, read on the UI thread. */
internal data class PreparedTextLayout(
val layout: Layout,
val sourceText: CharSequence,
val verticalOffset: Float
)

/** Reads the optional RN text implementation without linking older RN apps to its classes. */
internal class PreparedTextLayoutReader {
private var accessors: Accessors? = null
private var resolved: Boolean = false
private var failureLogged: Boolean = false

/** Returns null while a layout is unavailable, or if its API cannot be read safely. */
fun read(view: View, logger: InternalLogger): PreparedTextLayout? {
return try {
if (!resolved) {
resolved = true
accessors = resolveAccessors(view.javaClass)
}
val methods = accessors ?: return null
val prepared = methods.preparedLayout.invoke(view) ?: return null
val layout = methods.layout.invoke(prepared) as? Layout ?: return null
val sourceText = methods.text.invoke(view) as? CharSequence ?: return null
val offset = (methods.verticalOffset.invoke(prepared) as? Number)?.toFloat() ?: 0f
PreparedTextLayout(layout, sourceText, offset)
} catch (error: ReflectiveOperationException) {
logFailure(logger, error)
null
} catch (error: SecurityException) {
logFailure(logger, error)
null
}
}

private fun resolveAccessors(viewClass: Class<*>): Accessors {
val preparedLayout = viewClass.getMethod("getPreparedLayout")
val preparedClass = preparedLayout.returnType
return Accessors(
preparedLayout,
viewClass.getMethod("getText"),
preparedClass.getMethod("getLayout"),
preparedClass.getMethod("getVerticalOffset")
)
}

private fun logFailure(logger: InternalLogger, error: Exception) {
if (!failureLogged) {
failureLogged = true
logger.log(
level = InternalLogger.Level.WARN,
targets = listOf(InternalLogger.Target.MAINTAINER, InternalLogger.Target.TELEMETRY),
messageBuilder = { "Unable to read React Native prepared text layout" },
throwable = error
)
}
}

private data class Accessors(
val preparedLayout: Method,
val text: Method,
val layout: Method,
val verticalOffset: Method
)
}
Loading