Stub Logic of Paper Text ShadowNodes (#55438)

Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/55438

All of this is dead, but still uses the text infra by Fabric that we continue to change. Lets stub out the internals of the ShadowNodes, to make it easier to edit RN text internals, and shave some code/space.

mdvacca or cortinico should be able to tell if this will cause issues with interop layer.

Changelog: [Internal]

Reviewed By: cortinico

Differential Revision: D92481655

fbshipit-source-id: 739adef324289d2bcfa80fe2698fe03f9fb65716
This commit is contained in:
Nick Gerleman authored and meta-codesync[bot] committed 2026-02-07 17:15:57 -08:00
1 parent 7e7f491c94
commit 125977196a
4 files changed
+174 -1037

No files matched your search

@@ -6073,80 +6073,32 @@ public abstract class com/facebook/react/views/text/ReactBaseTextShadowNode : co
public fun <init> ()V
public fun <init> (Lcom/facebook/react/views/text/ReactTextViewManagerCallback;)V
public synthetic fun <init> (Lcom/facebook/react/views/text/ReactTextViewManagerCallback;ILkotlin/jvm/internal/DefaultConstructorMarker;)V
protected final fun getAccessibilityRole ()Lcom/facebook/react/uimanager/ReactAccessibilityDelegate$AccessibilityRole;
protected final fun getAdjustsFontSizeToFit ()Z
protected final fun getBackgroundColor ()I
protected final fun getColor ()I
protected final fun getContainsImages ()Z
protected final fun getFontFamily ()Ljava/lang/String;
protected final fun getFontFeatureSettings ()Ljava/lang/String;
protected final fun getFontStyle ()I
protected final fun getFontWeight ()I
protected final fun getHyphenationFrequency ()I
protected final fun getIncludeFontPadding ()Z
protected final fun getInlineViews ()Ljava/util/Map;
protected final fun getJustificationMode ()I
protected final fun getMinimumFontScale ()F
protected final fun getNumberOfLines ()I
protected final fun getReactTextViewManagerCallback ()Lcom/facebook/react/views/text/ReactTextViewManagerCallback;
protected final fun getRole ()Lcom/facebook/react/uimanager/ReactAccessibilityDelegate$Role;
protected final fun getTextAlign ()I
protected final fun getTextAttributes ()Lcom/facebook/react/views/text/TextAttributes;
protected final fun getTextBreakStrategy ()I
protected final fun getTextShadowColor ()I
protected final fun getTextShadowOffsetDx ()F
protected final fun getTextShadowOffsetDy ()F
protected final fun getTextShadowRadius ()F
protected final fun isBackgroundColorSet ()Z
protected final fun isColorSet ()Z
protected final fun isLineThroughTextDecorationSet ()Z
protected final fun isUnderlineTextDecorationSet ()Z
protected final fun setAccessibilityRole (Lcom/facebook/react/uimanager/ReactAccessibilityDelegate$AccessibilityRole;)V
public final fun setAccessibilityRole (Ljava/lang/String;)V
public final fun setAdjustFontSizeToFit (Z)V
protected final fun setAdjustsFontSizeToFit (Z)V
public final fun setAllowFontScaling (Z)V
protected final fun setBackgroundColor (I)V
public final fun setBackgroundColor (Ljava/lang/Integer;)V
protected final fun setBackgroundColorSet (Z)V
protected final fun setColor (I)V
public final fun setColor (Ljava/lang/Integer;)V
protected final fun setColorSet (Z)V
protected final fun setContainsImages (Z)V
public final fun setFontFamily (Ljava/lang/String;)V
protected final fun setFontFeatureSettings (Ljava/lang/String;)V
public final fun setFontSize (F)V
protected final fun setFontStyle (I)V
public final fun setFontStyle (Ljava/lang/String;)V
public final fun setFontVariant (Lcom/facebook/react/bridge/ReadableArray;)V
protected final fun setFontWeight (I)V
public final fun setFontWeight (Ljava/lang/String;)V
protected final fun setHyphenationFrequency (I)V
public final fun setIncludeFontPadding (Z)V
protected final fun setInlineViews (Ljava/util/Map;)V
protected final fun setJustificationMode (I)V
public final fun setLetterSpacing (F)V
public final fun setLineHeight (F)V
protected final fun setLineThroughTextDecorationSet (Z)V
public final fun setMaxFontSizeMultiplier (F)V
public final fun setMinimumFontScale (F)V
public final fun setNumberOfLines (I)V
protected final fun setReactTextViewManagerCallback (Lcom/facebook/react/views/text/ReactTextViewManagerCallback;)V
protected final fun setRole (Lcom/facebook/react/uimanager/ReactAccessibilityDelegate$Role;)V
public final fun setRole (Ljava/lang/String;)V
public final fun setTextAlign (Ljava/lang/String;)V
protected final fun setTextAttributes (Lcom/facebook/react/views/text/TextAttributes;)V
protected final fun setTextBreakStrategy (I)V
public fun setTextBreakStrategy (Ljava/lang/String;)V
public final fun setTextDecorationLine (Ljava/lang/String;)V
public final fun setTextShadowColor (I)V
public final fun setTextShadowOffset (Lcom/facebook/react/bridge/ReadableMap;)V
protected final fun setTextShadowOffsetDx (F)V
protected final fun setTextShadowOffsetDy (F)V
public final fun setTextShadowRadius (F)V
public final fun setTextTransform (Ljava/lang/String;)V
protected final fun setUnderlineTextDecorationSet (Z)V
protected final fun spannedFromShadowNode (Lcom/facebook/react/views/text/ReactBaseTextShadowNode;Ljava/lang/String;ZLcom/facebook/react/uimanager/NativeViewHierarchyOptimizer;)Landroid/text/Spannable;
}
public final class com/facebook/react/views/text/ReactBaseTextShadowNode$Companion {
@@ -9,47 +9,16 @@
package com.facebook.react.views.text
import android.graphics.Color
import android.os.Build
import android.text.Layout
import android.text.Spannable
import android.text.SpannableStringBuilder
import android.view.Gravity
import com.facebook.common.logging.FLog
import com.facebook.react.bridge.ReadableArray
import com.facebook.react.bridge.ReadableMap
import com.facebook.react.common.ReactConstants
import com.facebook.react.common.annotations.internal.LegacyArchitecture
import com.facebook.react.common.annotations.internal.LegacyArchitectureLogLevel
import com.facebook.react.uimanager.IllegalViewOperationException
import com.facebook.react.uimanager.LayoutShadowNode
import com.facebook.react.uimanager.PixelUtil.toPixelFromDIP
import com.facebook.react.uimanager.ReactAccessibilityDelegate
import com.facebook.react.uimanager.ReactAccessibilityDelegate.AccessibilityRole
import com.facebook.react.uimanager.ReactShadowNode
import com.facebook.react.uimanager.ReactShadowNodeImpl
import com.facebook.react.uimanager.ViewProps
import com.facebook.react.uimanager.annotations.ReactProp
import com.facebook.react.views.text.ReactTypefaceUtils.parseFontStyle
import com.facebook.react.views.text.ReactTypefaceUtils.parseFontVariant
import com.facebook.react.views.text.ReactTypefaceUtils.parseFontWeight
import com.facebook.react.views.text.TextTransform.Companion.apply
import com.facebook.react.views.text.internal.span.CustomLetterSpacingSpan
import com.facebook.react.views.text.internal.span.CustomLineHeightSpan
import com.facebook.react.views.text.internal.span.CustomStyleSpan
import com.facebook.react.views.text.internal.span.ReactAbsoluteSizeSpan
import com.facebook.react.views.text.internal.span.ReactBackgroundColorSpan
import com.facebook.react.views.text.internal.span.ReactClickableSpan
import com.facebook.react.views.text.internal.span.ReactForegroundColorSpan
import com.facebook.react.views.text.internal.span.ReactStrikethroughSpan
import com.facebook.react.views.text.internal.span.ReactTagSpan
import com.facebook.react.views.text.internal.span.ReactUnderlineSpan
import com.facebook.react.views.text.internal.span.SetSpanOperation
import com.facebook.react.views.text.internal.span.ShadowStyleSpan
import com.facebook.react.views.text.internal.span.TextInlineImageSpan
import com.facebook.react.views.text.internal.span.TextInlineViewPlaceholderSpan
import com.facebook.yoga.YogaDirection
import com.facebook.yoga.YogaUnit
/**
* [ReactShadowNode] abstract class for spannable text nodes.
@@ -70,430 +39,199 @@ public abstract class ReactBaseTextShadowNode
public constructor(
protected var reactTextViewManagerCallback: ReactTextViewManagerCallback? = null
) : LayoutShadowNode() {
protected var textAttributes: TextAttributes = TextAttributes()
protected var isColorSet: Boolean = false
protected var color: Int = 0
protected var isBackgroundColorSet: Boolean = false
protected var backgroundColor: Int = 0
protected var accessibilityRole: AccessibilityRole? = null
protected var role: ReactAccessibilityDelegate.Role? = null
protected var numberOfLines: Int = ReactConstants.UNSET
private set
protected var textBreakStrategy: Int = Layout.BREAK_STRATEGY_HIGH_QUALITY
protected var hyphenationFrequency: Int = Layout.HYPHENATION_FREQUENCY_NONE
protected var justificationMode: Int =
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
0
} else {
Layout.JUSTIFICATION_MODE_NONE
}
// Return text alignment according to LTR or RTL style
protected var textAlign: Int = Gravity.NO_GRAVITY
get() {
return if (layoutDirection == YogaDirection.RTL) {
when (field) {
Gravity.RIGHT -> Gravity.LEFT
Gravity.LEFT -> Gravity.RIGHT
else -> field
}
} else {
field
}
}
private set
/**
* [fontStyle] can be [Typeface.NORMAL] or [Typeface.ITALIC]. [fontWeight] can be
* [Typeface.NORMAL] or [Typeface.BOLD].
*/
protected var fontStyle: Int = ReactConstants.UNSET
protected var fontWeight: Int = ReactConstants.UNSET
/**
* NB: If a font family is used that does not have a style in a certain Android version (ie.
* monospace bold pre Android 5.0), that style (ie. bold) will not be inherited by nested Text
* nodes. To retain that style, you have to add it to those nodes explicitly.
*
* Example, Android 4.4:
* <pre>
* <Text style={{fontFamily="serif" fontWeight="bold" }}>Bold Text</Text>
* <Text style={{fontFamily="sans-serif"}}>Bold Text</Text>
* <Text style={{fontFamily="serif"}}>Bold Text</Text>
*
* <Text style={{fontFamily="monospace" fontWeight="bold" }}>Not Bold Text</Text>
* <Text style={{fontFamily="sans-serif"}}>Not Bold Text</Text>
* <Text style={{fontFamily="serif"}}>Not Bold Text</Text>
*
* <Text style={{fontFamily="monospace" fontWeight="bold" }}>Not Bold Text</Text>
* <Text style={{fontFamily="sans-serif" fontWeight="bold" }}>Bold Text</Text>
* <Text style={{fontFamily="serif"}}>Bold Text</Text>
* </pre>
*/
protected var fontFamily: String? = null
private set
/** @see [android.graphics.Paint.setFontFeatureSettings] */
protected var fontFeatureSettings: String? = null
protected var includeFontPadding: Boolean = true
private set
protected var adjustsFontSizeToFit: Boolean = false
protected var minimumFontScale: Float = 0f
private set
protected var textShadowOffsetDx: Float = 0f
protected var textShadowOffsetDy: Float = 0f
protected var textShadowRadius: Float = 0f
private set
protected var textShadowColor: Int = DEFAULT_TEXT_SHADOW_COLOR
private set
protected var isUnderlineTextDecorationSet: Boolean = false
protected var isLineThroughTextDecorationSet: Boolean = false
protected var containsImages: Boolean = false
// Only nullable if `supportsInlineViews` is `false`.
protected var inlineViews: Map<Int, ReactShadowNode<*>>? = null
// `nativeViewHierarchyOptimizer` can be `null` as long as `supportsInlineViews` is `false`.
@Suppress("DEPRECATION")
protected fun spannedFromShadowNode(
textShadowNode: ReactBaseTextShadowNode,
text: String?,
supportsInlineViews: Boolean,
nativeViewHierarchyOptimizer: com.facebook.react.uimanager.NativeViewHierarchyOptimizer?,
): Spannable {
check(!supportsInlineViews || nativeViewHierarchyOptimizer != null) {
"nativeViewHierarchyOptimizer is required when inline views are supported"
}
val sb = SpannableStringBuilder()
// TODO(5837930): Investigate whether it's worth optimizing this part and do it if so
// The [SpannableStringBuilder] implementation require setSpan operation to be called
// up-to-bottom, otherwise all the spannables that are within the region for which one may set
// a new spannable will be wiped out
val ops: MutableList<SetSpanOperation> = ArrayList()
val inlineViews: MutableMap<Int, ReactShadowNode<*>>? =
if (supportsInlineViews) HashMap() else null
if (text != null) {
// Handle text that is provided via a prop (e.g. the `value` and `defaultValue` props on
// TextInput).
sb.append(apply(text, textShadowNode.textAttributes.textTransform))
}
buildSpannedFromShadowNode(textShadowNode, sb, ops, null, supportsInlineViews, inlineViews, 0)
textShadowNode.containsImages = false
textShadowNode.inlineViews = inlineViews
var heightOfTallestInlineViewOrImage = Float.NaN
// While setting the Spans on the final text, we also check whether any of them are inline views
// or images.
for (priorityIndex in ops.indices) {
val op = ops[ops.size - priorityIndex - 1]
val what = op.what
val isInlineImage = what is TextInlineImageSpan
if (isInlineImage || what is TextInlineViewPlaceholderSpan) {
val height: Int
if (isInlineImage) {
height = what.height
textShadowNode.containsImages = true
} else {
val placeholder = what as TextInlineViewPlaceholderSpan
height = placeholder.height
// Inline views cannot be layout-only because ReactTextView needs to access
// them on the UI thread to measure and position them.
val childNode = checkNotNull(inlineViews)[placeholder.reactTag]
checkNotNull(childNode)
checkNotNull(nativeViewHierarchyOptimizer)
nativeViewHierarchyOptimizer.handleForceViewToBeNonLayoutOnly(childNode)
// The ReactTextView is responsible for laying out the inline views.
@Suppress("UNCHECKED_CAST")
(childNode as ReactShadowNode<ReactShadowNodeImpl>).setLayoutParent(textShadowNode)
}
if (heightOfTallestInlineViewOrImage.isNaN() || height > heightOfTallestInlineViewOrImage) {
heightOfTallestInlineViewOrImage = height.toFloat()
}
}
// Actual order of calling `execute` does NOT matter,
// but the `priorityIndex` DOES matter.
op.execute(sb, priorityIndex)
}
textShadowNode.textAttributes.heightOfTallestInlineViewOrImage =
heightOfTallestInlineViewOrImage
reactTextViewManagerCallback?.onPostProcessSpannable(sb)
return sb
}
@Suppress("UNUSED_PARAMETER")
@ReactProp(name = ViewProps.NUMBER_OF_LINES, defaultInt = ReactConstants.UNSET)
public fun setNumberOfLines(numberOfLines: Int) {
this.numberOfLines = if (numberOfLines == 0) ReactConstants.UNSET else numberOfLines
markUpdated()
error(
"ReactBaseTextShadowNode methods are unsupported, and the ShadowNode will be fully removed in a future version of React Native."
)
}
@Suppress("UNUSED_PARAMETER")
@ReactProp(name = ViewProps.LINE_HEIGHT, defaultFloat = Float.NaN)
public fun setLineHeight(lineHeight: Float) {
textAttributes.lineHeight = lineHeight
markUpdated()
error(
"ReactBaseTextShadowNode methods are unsupported, and the ShadowNode will be fully removed in a future version of React Native."
)
}
@Suppress("UNUSED_PARAMETER")
@ReactProp(name = ViewProps.LETTER_SPACING, defaultFloat = 0f)
public fun setLetterSpacing(letterSpacing: Float) {
textAttributes.letterSpacing = letterSpacing
markUpdated()
error(
"ReactBaseTextShadowNode methods are unsupported, and the ShadowNode will be fully removed in a future version of React Native."
)
}
@Suppress("UNUSED_PARAMETER")
@ReactProp(name = ViewProps.ALLOW_FONT_SCALING, defaultBoolean = true)
public fun setAllowFontScaling(allowFontScaling: Boolean) {
if (allowFontScaling != textAttributes.allowFontScaling) {
textAttributes.allowFontScaling = allowFontScaling
markUpdated()
}
error(
"ReactBaseTextShadowNode methods are unsupported, and the ShadowNode will be fully removed in a future version of React Native."
)
}
@Suppress("UNUSED_PARAMETER")
@ReactProp(name = ViewProps.MAX_FONT_SIZE_MULTIPLIER, defaultFloat = Float.NaN)
public fun setMaxFontSizeMultiplier(maxFontSizeMultiplier: Float) {
if (maxFontSizeMultiplier != textAttributes.maxFontSizeMultiplier) {
textAttributes.maxFontSizeMultiplier = maxFontSizeMultiplier
markUpdated()
}
error(
"ReactBaseTextShadowNode methods are unsupported, and the ShadowNode will be fully removed in a future version of React Native."
)
}
@Suppress("UNUSED_PARAMETER")
@ReactProp(name = ViewProps.TEXT_ALIGN)
public fun setTextAlign(textAlign: String?) {
if ("justify" == textAlign) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
justificationMode = Layout.JUSTIFICATION_MODE_INTER_WORD
}
this.textAlign = Gravity.LEFT
} else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
justificationMode = Layout.JUSTIFICATION_MODE_NONE
}
this.textAlign =
when (textAlign) {
null,
"auto" -> Gravity.NO_GRAVITY
"left" -> Gravity.LEFT
"right" -> Gravity.RIGHT
"center" -> Gravity.CENTER_HORIZONTAL
else -> {
FLog.w(ReactConstants.TAG, "Invalid textAlign: $textAlign")
Gravity.NO_GRAVITY
}
}
}
markUpdated()
error(
"ReactBaseTextShadowNode methods are unsupported, and the ShadowNode will be fully removed in a future version of React Native."
)
}
@Suppress("UNUSED_PARAMETER")
@ReactProp(name = ViewProps.FONT_SIZE, defaultFloat = Float.NaN)
public fun setFontSize(fontSize: Float) {
textAttributes.fontSize = fontSize
markUpdated()
error(
"ReactBaseTextShadowNode methods are unsupported, and the ShadowNode will be fully removed in a future version of React Native."
)
}
@Suppress("UNUSED_PARAMETER")
@ReactProp(name = ViewProps.COLOR, customType = "Color")
public fun setColor(color: Int?) {
color?.let { newColor ->
isColorSet = true
this.color = newColor
}
markUpdated()
error(
"ReactBaseTextShadowNode methods are unsupported, and the ShadowNode will be fully removed in a future version of React Native."
)
}
@Suppress("UNUSED_PARAMETER")
@ReactProp(name = ViewProps.BACKGROUND_COLOR, customType = "Color")
public fun setBackgroundColor(color: Int?) {
// Background color needs to be handled here for virtual nodes so it can be incorporated into
// the span. However, it doesn't need to be applied to non-virtual nodes because non-virtual
// nodes get mapped to native views and native views get their background colors get set via
// [BaseViewManager].
if (isVirtual) {
color?.let { newColor ->
isBackgroundColorSet = true
backgroundColor = newColor
}
markUpdated()
}
error(
"ReactBaseTextShadowNode methods are unsupported, and the ShadowNode will be fully removed in a future version of React Native."
)
}
@Suppress("UNUSED_PARAMETER")
@ReactProp(name = ViewProps.ACCESSIBILITY_ROLE)
public fun setAccessibilityRole(accessibilityRole: String?) {
if (isVirtual) {
this.accessibilityRole = AccessibilityRole.fromValue(accessibilityRole)
markUpdated()
}
error(
"ReactBaseTextShadowNode methods are unsupported, and the ShadowNode will be fully removed in a future version of React Native."
)
}
@Suppress("UNUSED_PARAMETER")
@ReactProp(name = ViewProps.ROLE)
public fun setRole(role: String?) {
if (isVirtual) {
this.role = ReactAccessibilityDelegate.Role.fromValue(role)
markUpdated()
}
error(
"ReactBaseTextShadowNode methods are unsupported, and the ShadowNode will be fully removed in a future version of React Native."
)
}
@Suppress("UNUSED_PARAMETER")
@ReactProp(name = ViewProps.FONT_FAMILY)
public fun setFontFamily(fontFamily: String?) {
this.fontFamily = fontFamily
markUpdated()
error(
"ReactBaseTextShadowNode methods are unsupported, and the ShadowNode will be fully removed in a future version of React Native."
)
}
@Suppress("UNUSED_PARAMETER")
@ReactProp(name = ViewProps.FONT_WEIGHT)
public fun setFontWeight(fontWeightString: String?) {
val parsedFontWeight = parseFontWeight(fontWeightString)
if (parsedFontWeight != fontWeight) {
fontWeight = parsedFontWeight
markUpdated()
}
error(
"ReactBaseTextShadowNode methods are unsupported, and the ShadowNode will be fully removed in a future version of React Native."
)
}
@Suppress("UNUSED_PARAMETER")
@ReactProp(name = ViewProps.FONT_VARIANT)
public fun setFontVariant(fontVariantArray: ReadableArray?) {
val fontFeatureSettings = parseFontVariant(fontVariantArray)
if (fontFeatureSettings != this.fontFeatureSettings) {
this.fontFeatureSettings = fontFeatureSettings
markUpdated()
}
error(
"ReactBaseTextShadowNode methods are unsupported, and the ShadowNode will be fully removed in a future version of React Native."
)
}
@Suppress("UNUSED_PARAMETER")
@ReactProp(name = ViewProps.FONT_STYLE)
public fun setFontStyle(fontStyleString: String?) {
val parsedFontStyle = parseFontStyle(fontStyleString)
if (parsedFontStyle != fontStyle) {
fontStyle = parsedFontStyle
markUpdated()
}
error(
"ReactBaseTextShadowNode methods are unsupported, and the ShadowNode will be fully removed in a future version of React Native."
)
}
@Suppress("UNUSED_PARAMETER")
@ReactProp(name = ViewProps.INCLUDE_FONT_PADDING, defaultBoolean = true)
public fun setIncludeFontPadding(includepad: Boolean) {
includeFontPadding = includepad
error(
"ReactBaseTextShadowNode methods are unsupported, and the ShadowNode will be fully removed in a future version of React Native."
)
}
@Suppress("UNUSED_PARAMETER")
@ReactProp(name = ViewProps.TEXT_DECORATION_LINE)
public fun setTextDecorationLine(textDecorationLineString: String?) {
isUnderlineTextDecorationSet = false
isLineThroughTextDecorationSet = false
if (textDecorationLineString != null) {
for (textDecorationLineSubString in
textDecorationLineString.split(" ").dropLastWhile { it.isEmpty() }.toTypedArray()) {
if ("underline" == textDecorationLineSubString) {
isUnderlineTextDecorationSet = true
} else if ("line-through" == textDecorationLineSubString) {
isLineThroughTextDecorationSet = true
}
}
}
markUpdated()
error(
"ReactBaseTextShadowNode methods are unsupported, and the ShadowNode will be fully removed in a future version of React Native."
)
}
@Suppress("UNUSED_PARAMETER")
@ReactProp(name = ViewProps.TEXT_BREAK_STRATEGY)
public open fun setTextBreakStrategy(textBreakStrategy: String?) {
this.textBreakStrategy =
when (textBreakStrategy) {
null,
"highQuality" -> Layout.BREAK_STRATEGY_HIGH_QUALITY
"simple" -> Layout.BREAK_STRATEGY_SIMPLE
"balanced" -> Layout.BREAK_STRATEGY_BALANCED
else -> {
FLog.w(ReactConstants.TAG, "Invalid textBreakStrategy: $textBreakStrategy")
Layout.BREAK_STRATEGY_HIGH_QUALITY
}
}
markUpdated()
error(
"ReactBaseTextShadowNode methods are unsupported, and the ShadowNode will be fully removed in a future version of React Native."
)
}
@Suppress("UNUSED_PARAMETER")
@ReactProp(name = PROP_SHADOW_OFFSET)
public fun setTextShadowOffset(offsetMap: ReadableMap?) {
textShadowOffsetDx = 0f
textShadowOffsetDy = 0f
offsetMap?.let { map ->
if (map.hasKey(PROP_SHADOW_OFFSET_WIDTH) && !map.isNull(PROP_SHADOW_OFFSET_WIDTH)) {
textShadowOffsetDx = toPixelFromDIP(map.getDouble(PROP_SHADOW_OFFSET_WIDTH))
}
if (map.hasKey(PROP_SHADOW_OFFSET_HEIGHT) && !map.isNull(PROP_SHADOW_OFFSET_HEIGHT)) {
textShadowOffsetDy = toPixelFromDIP(map.getDouble(PROP_SHADOW_OFFSET_HEIGHT))
}
}
markUpdated()
error(
"ReactBaseTextShadowNode methods are unsupported, and the ShadowNode will be fully removed in a future version of React Native."
)
}
@Suppress("UNUSED_PARAMETER")
@ReactProp(name = PROP_SHADOW_RADIUS, defaultInt = 1)
public fun setTextShadowRadius(textShadowRadius: Float) {
if (textShadowRadius != this.textShadowRadius) {
this.textShadowRadius = textShadowRadius
markUpdated()
}
error(
"ReactBaseTextShadowNode methods are unsupported, and the ShadowNode will be fully removed in a future version of React Native."
)
}
@Suppress("UNUSED_PARAMETER")
@ReactProp(name = PROP_SHADOW_COLOR, defaultInt = DEFAULT_TEXT_SHADOW_COLOR, customType = "Color")
public fun setTextShadowColor(textShadowColor: Int) {
if (textShadowColor != this.textShadowColor) {
this.textShadowColor = textShadowColor
markUpdated()
}
error(
"ReactBaseTextShadowNode methods are unsupported, and the ShadowNode will be fully removed in a future version of React Native."
)
}
@Suppress("UNUSED_PARAMETER")
@ReactProp(name = PROP_TEXT_TRANSFORM)
public fun setTextTransform(textTransform: String?) {
val textTransformEnum =
when (textTransform) {
null -> TextTransform.UNSET
"none" -> TextTransform.NONE
"uppercase" -> TextTransform.UPPERCASE
"lowercase" -> TextTransform.LOWERCASE
"capitalize" -> TextTransform.CAPITALIZE
else -> {
FLog.w(ReactConstants.TAG, "Invalid textTransform: $textTransform")
TextTransform.UNSET
}
}
textAttributes.textTransform = textTransformEnum
markUpdated()
error(
"ReactBaseTextShadowNode methods are unsupported, and the ShadowNode will be fully removed in a future version of React Native."
)
}
@Suppress("UNUSED_PARAMETER")
@ReactProp(name = ViewProps.ADJUSTS_FONT_SIZE_TO_FIT)
public fun setAdjustFontSizeToFit(adjustsFontSizeToFit: Boolean) {
if (adjustsFontSizeToFit != this.adjustsFontSizeToFit) {
this.adjustsFontSizeToFit = adjustsFontSizeToFit
markUpdated()
}
error(
"ReactBaseTextShadowNode methods are unsupported, and the ShadowNode will be fully removed in a future version of React Native."
)
}
@Suppress("UNUSED_PARAMETER")
@ReactProp(name = ViewProps.MINIMUM_FONT_SCALE)
public fun setMinimumFontScale(minimumFontScale: Float) {
if (minimumFontScale != this.minimumFontScale) {
this.minimumFontScale = minimumFontScale
markUpdated()
}
error(
"ReactBaseTextShadowNode methods are unsupported, and the ShadowNode will be fully removed in a future version of React Native."
)
}
public companion object {
// Use a direction weak character so the placeholder doesn't change the direction of the
// previous character. https://en.wikipedia.org/wiki/Bi-directional_text#weak_characters
private const val INLINE_VIEW_PLACEHOLDER = "0"
public const val PROP_SHADOW_OFFSET: String = "textShadowOffset"
public const val PROP_SHADOW_OFFSET_WIDTH: String = "width"
public const val PROP_SHADOW_OFFSET_HEIGHT: String = "height"
@@ -503,175 +241,5 @@ public constructor(
public const val PROP_TEXT_TRANSFORM: String = "textTransform"
public const val DEFAULT_TEXT_SHADOW_COLOR: Int = 0x55000000
private fun buildSpannedFromShadowNode(
textShadowNode: ReactBaseTextShadowNode,
sb: SpannableStringBuilder,
ops: MutableList<SetSpanOperation>,
parentTextAttributes: TextAttributes?,
supportsInlineViews: Boolean,
inlineViews: MutableMap<Int, ReactShadowNode<*>>?,
start: Int,
) {
val textAttributes =
parentTextAttributes?.applyChild(textShadowNode.textAttributes)
?: textShadowNode.textAttributes
var i = 0
val length = textShadowNode.childCount
while (i < length) {
val child: ReactShadowNode<*> = textShadowNode.getChildAt(i)
@Suppress("DEPRECATION")
if (child is ReactBaseTextShadowNode) {
buildSpannedFromShadowNode(
child,
sb,
ops,
textAttributes,
supportsInlineViews,
inlineViews,
sb.length,
)
} else if (child is com.facebook.react.views.text.internal.ReactTextInlineImageShadowNode) {
// We make the image take up 1 character in the span and put a corresponding character
// into the text so that the image doesn't run over any following text.
sb.append(INLINE_VIEW_PLACEHOLDER)
ops.add(
SetSpanOperation(
sb.length - INLINE_VIEW_PLACEHOLDER.length,
sb.length,
child.buildInlineImageSpan(),
)
)
} else if (supportsInlineViews) {
val reactTag = child.reactTag
val widthValue = child.styleWidth
val heightValue = child.styleHeight
val width: Float
val height: Float
if (widthValue.unit != YogaUnit.POINT || heightValue.unit != YogaUnit.POINT) {
// If the measurement of the child isn't calculated, we calculate the layout for the
// view using Yoga
child.calculateLayout()
width = child.layoutWidth
height = child.layoutHeight
} else {
width = widthValue.value
height = heightValue.value
}
// We make the inline view take up 1 character in the span and put a corresponding
// character
// into
// the text so that the inline view doesn't run over any following text.
sb.append(INLINE_VIEW_PLACEHOLDER)
ops.add(
SetSpanOperation(
sb.length - INLINE_VIEW_PLACEHOLDER.length,
sb.length,
TextInlineViewPlaceholderSpan(reactTag, width.toInt(), height.toInt()),
)
)
// supportsInlineViews is true, so we can assume that inlineViews is not null
checkNotNull(inlineViews)[reactTag] = child
} else {
throw IllegalViewOperationException(
"Unexpected view type nested under a <Text> or <TextInput> node: ${child.javaClass}"
)
}
child.markUpdateSeen()
i++
}
val end = sb.length
if (end >= start) {
if (textShadowNode.isColorSet) {
ops.add(SetSpanOperation(start, end, ReactForegroundColorSpan(textShadowNode.color)))
}
if (textShadowNode.isBackgroundColorSet) {
ops.add(
SetSpanOperation(start, end, ReactBackgroundColorSpan(textShadowNode.backgroundColor))
)
}
val roleIsLink =
if (textShadowNode.role != null)
textShadowNode.role == ReactAccessibilityDelegate.Role.LINK
else textShadowNode.accessibilityRole == AccessibilityRole.LINK
if (roleIsLink) {
ops.add(SetSpanOperation(start, end, ReactClickableSpan(textShadowNode.reactTag)))
}
val effectiveLetterSpacing = textAttributes.effectiveLetterSpacing
if (
!java.lang.Float.isNaN(effectiveLetterSpacing) &&
(parentTextAttributes == null ||
parentTextAttributes.effectiveLetterSpacing != effectiveLetterSpacing)
) {
ops.add(SetSpanOperation(start, end, CustomLetterSpacingSpan(effectiveLetterSpacing)))
}
val effectiveFontSize = textAttributes.effectiveFontSize
if ( // `getEffectiveFontSize` always returns a value so don't need to check for anything
// like `Float.NaN`.
parentTextAttributes == null ||
parentTextAttributes.effectiveFontSize != effectiveFontSize
) {
ops.add(SetSpanOperation(start, end, ReactAbsoluteSizeSpan(effectiveFontSize)))
}
if (
textShadowNode.fontStyle != ReactConstants.UNSET ||
textShadowNode.fontWeight != ReactConstants.UNSET ||
textShadowNode.fontFamily != null
) {
ops.add(
SetSpanOperation(
start,
end,
CustomStyleSpan(
textShadowNode.fontStyle,
textShadowNode.fontWeight,
textShadowNode.fontFeatureSettings,
textShadowNode.fontFamily,
textShadowNode.themedContext.assets,
),
)
)
}
if (textShadowNode.isUnderlineTextDecorationSet) {
ops.add(SetSpanOperation(start, end, ReactUnderlineSpan()))
}
if (textShadowNode.isLineThroughTextDecorationSet) {
ops.add(SetSpanOperation(start, end, ReactStrikethroughSpan()))
}
if (
(textShadowNode.textShadowOffsetDx != 0f ||
textShadowNode.textShadowOffsetDy != 0f ||
textShadowNode.textShadowRadius != 0f) &&
Color.alpha(textShadowNode.textShadowColor) != 0
) {
ops.add(
SetSpanOperation(
start,
end,
ShadowStyleSpan(
textShadowNode.textShadowOffsetDx,
textShadowNode.textShadowOffsetDy,
textShadowNode.textShadowRadius,
textShadowNode.textShadowColor,
),
)
)
}
val effectiveLineHeight = textAttributes.effectiveLineHeight
if (
!java.lang.Float.isNaN(effectiveLineHeight) &&
(parentTextAttributes == null ||
parentTextAttributes.effectiveLineHeight != effectiveLineHeight)
) {
ops.add(SetSpanOperation(start, end, CustomLineHeightSpan(effectiveLineHeight)))
}
ops.add(SetSpanOperation(start, end, ReactTagSpan(textShadowNode.reactTag)))
}
}
}
}
@@ -5,45 +5,16 @@
* LICENSE file in the root directory of this source tree.
*/
@file:Suppress(
"DEPRECATION"
) // silents "interface RCTEventEmitter : JavaScriptModule' is deprecated."
@file:Suppress("DEPRECATION")
package com.facebook.react.views.text
import android.os.Build
import android.text.BoringLayout
import android.text.Layout
import android.text.Spannable
import android.text.Spanned
import android.text.StaticLayout
import android.text.TextPaint
import android.view.Gravity
import com.facebook.react.bridge.Arguments
import com.facebook.react.bridge.ReactNoCrashSoftException
import com.facebook.react.bridge.ReactSoftExceptionLogger.logSoftException
import com.facebook.react.common.ReactConstants
import com.facebook.react.common.annotations.internal.LegacyArchitecture
import com.facebook.react.common.annotations.internal.LegacyArchitectureLogLevel
import com.facebook.react.uimanager.NativeViewHierarchyOptimizer
import com.facebook.react.uimanager.PixelUtil
import com.facebook.react.uimanager.ReactShadowNode
import com.facebook.react.uimanager.Spacing
import com.facebook.react.uimanager.UIViewOperationQueue
import com.facebook.react.uimanager.annotations.ReactProp
import com.facebook.react.uimanager.events.RCTEventEmitter
import com.facebook.react.views.text.FontMetricsUtil.getFontMetrics
import com.facebook.react.views.text.internal.span.ReactAbsoluteSizeSpan
import com.facebook.react.views.text.internal.span.TextInlineViewPlaceholderSpan
import com.facebook.yoga.YogaBaselineFunction
import com.facebook.yoga.YogaConstants
import com.facebook.yoga.YogaDirection
import com.facebook.yoga.YogaMeasureFunction
import com.facebook.yoga.YogaMeasureMode
import com.facebook.yoga.YogaMeasureOutput
import kotlin.math.ceil
import kotlin.math.max
import kotlin.math.min
/**
* [ReactBaseTextShadowNode] concrete class for anchor `Text` node.
@@ -60,310 +31,50 @@ public class ReactTextShadowNode
@JvmOverloads
public constructor(reactTextViewManagerCallback: ReactTextViewManagerCallback? = null) :
ReactBaseTextShadowNode(reactTextViewManagerCallback) {
private var preparedSpannableText: Spannable? = null
private var shouldNotifyOnTextLayout = false
private val textMeasureFunction = YogaMeasureFunction { _, width, widthMode, height, heightMode ->
val text =
requireNotNull(preparedSpannableText) {
"Spannable element has not been prepared in onBeforeLayout"
}
var layout = measureSpannedText(text, width, widthMode)
if (adjustsFontSizeToFit) {
val initialFontSize = textAttributes.effectiveFontSize
var currentFontSize = textAttributes.effectiveFontSize
// Minimum font size is 4pts to match the iOS implementation.
val minimumFontSize =
max((minimumFontScale * initialFontSize), PixelUtil.toPixelFromDIP(4f)).toInt()
while (
currentFontSize > minimumFontSize &&
((numberOfLines != ReactConstants.UNSET && layout.lineCount > numberOfLines) ||
(heightMode != YogaMeasureMode.UNDEFINED && layout.height > height))
) {
// TODO: We could probably use a smarter algorithm here. This will require 0(n)
// measurements
// based on the number of points the font size needs to be reduced by.
currentFontSize -= max(1, PixelUtil.toPixelFromDIP(1f).toInt())
val ratio = currentFontSize.toFloat() / initialFontSize.toFloat()
val sizeSpans = text.getSpans(0, text.length, ReactAbsoluteSizeSpan::class.java)
for (span in sizeSpans) {
text.setSpan(
ReactAbsoluteSizeSpan(
max((span.size * ratio).toDouble(), minimumFontSize.toDouble()).toInt()
),
text.getSpanStart(span),
text.getSpanEnd(span),
text.getSpanFlags(span),
)
text.removeSpan(span)
}
layout = measureSpannedText(text, width, widthMode)
}
}
if (shouldNotifyOnTextLayout) {
val themedReactContext = themedContext
val lines = getFontMetrics(text, layout, themedReactContext)
val event = Arguments.createMap().apply { putArray("lines", lines) }
if (themedReactContext.hasActiveReactInstance()) {
themedReactContext
.getJSModule(RCTEventEmitter::class.java)
.receiveEvent(reactTag, "topTextLayout", event)
} else {
logSoftException(
"ReactTextShadowNode",
ReactNoCrashSoftException("Cannot get RCTEventEmitter, no CatalystInstance"),
)
}
}
val lineCount =
if (numberOfLines == ReactConstants.UNSET) {
layout.lineCount
} else {
min(numberOfLines.toDouble(), layout.lineCount.toDouble()).toInt()
}
// Instead of using `layout.getWidth()` (which may yield a significantly larger width
// for
// text that is wrapping), compute width using the longest line.
var layoutWidth = 0f
if (widthMode == YogaMeasureMode.EXACTLY) {
layoutWidth = width
} else {
for (lineIndex in 0 until lineCount) {
val endsWithNewLine = text.length > 0 && text[layout.getLineEnd(lineIndex) - 1] == '\n'
val lineWidth =
if (endsWithNewLine) layout.getLineMax(lineIndex) else layout.getLineWidth(lineIndex)
if (lineWidth > layoutWidth) {
layoutWidth = lineWidth
}
}
if (widthMode == YogaMeasureMode.AT_MOST && layoutWidth > width) {
layoutWidth = width
}
}
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.Q) {
layoutWidth = ceil(layoutWidth.toDouble()).toFloat()
}
var layoutHeight = height
if (heightMode != YogaMeasureMode.EXACTLY) {
layoutHeight = layout.getLineBottom(lineCount - 1).toFloat()
if (heightMode == YogaMeasureMode.AT_MOST && layoutHeight > height) {
layoutHeight = height
}
}
YogaMeasureOutput.make(layoutWidth, layoutHeight)
override fun isVirtualAnchor(): Boolean {
error(
"ReactTextShadowNode methods are unsupported, and the ShadowNode will be fully removed in a future version of React Native."
)
}
private val textBaselineFunction = YogaBaselineFunction { node, width, height ->
val text =
checkNotNull(preparedSpannableText) {
"Spannable element has not been prepared in onBeforeLayout"
}
val layout = measureSpannedText(text, width, YogaMeasureMode.EXACTLY)
layout.getLineBaseline(layout.lineCount - 1).toFloat()
override fun hoistNativeChildren(): Boolean {
error(
"ReactTextShadowNode methods are unsupported, and the ShadowNode will be fully removed in a future version of React Native."
)
}
init {
initMeasureFunction()
}
private fun initMeasureFunction() {
if (!isVirtual) {
setMeasureFunction(textMeasureFunction)
setBaselineFunction(textBaselineFunction)
}
}
private fun measureSpannedText(
text: Spannable,
width: Float,
widthMode: YogaMeasureMode,
): Layout {
// TODO(5578671): Handle text direction (see View#getTextDirectionHeuristic)
var width = width
val textPaint = textPaintInstance
textPaint.textSize = textAttributes.effectiveFontSize.toFloat()
val layout: Layout
val boring = BoringLayout.isBoring(text, textPaint)
val desiredWidth = if (boring == null) Layout.getDesiredWidth(text, textPaint) else Float.NaN
// technically, width should never be negative, but there is currently a bug in
val unconstrainedWidth = widthMode == YogaMeasureMode.UNDEFINED || width < 0
val alignment =
when (_textAlign) {
Gravity.LEFT -> Layout.Alignment.ALIGN_NORMAL
Gravity.RIGHT -> Layout.Alignment.ALIGN_OPPOSITE
Gravity.CENTER_HORIZONTAL -> Layout.Alignment.ALIGN_CENTER
else -> Layout.Alignment.ALIGN_NORMAL
}
if (
boring == null &&
(unconstrainedWidth ||
(!YogaConstants.isUndefined(desiredWidth) && desiredWidth <= width))
) {
// Is used when the width is not known and the text is not boring, ie. if it contains
// unicode characters.
val hintWidth = ceil(desiredWidth.toDouble()).toInt()
val builder =
StaticLayout.Builder.obtain(text, 0, text.length, textPaint, hintWidth)
.setAlignment(alignment)
.setLineSpacing(0f, 1f)
.setIncludePad(includeFontPadding)
.setBreakStrategy(textBreakStrategy)
.setHyphenationFrequency(hyphenationFrequency)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
builder.setJustificationMode(justificationMode)
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
builder.setUseLineSpacingFromFallbacks(true)
}
layout = builder.build()
} else if (boring != null && (unconstrainedWidth || boring.width <= width)) {
// Is used for single-line, boring text when the width is either unknown or bigger
// than the width of the text.
layout =
BoringLayout.make(
text,
textPaint,
max(boring.width.toDouble(), 0.0).toInt(),
alignment,
1f,
0f,
boring,
includeFontPadding,
)
} else {
// Is used for multiline, boring text and the width is known.
// Android 11+ introduces changes in text width calculation which leads to cases
// where the container is measured smaller than text. Math.ceil prevents it
// See T136756103 for investigation
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.Q) {
width = ceil(width.toDouble()).toFloat()
}
val builder =
StaticLayout.Builder.obtain(text, 0, text.length, textPaint, width.toInt())
.setAlignment(alignment)
.setLineSpacing(0f, 1f)
.setIncludePad(includeFontPadding)
.setBreakStrategy(textBreakStrategy)
.setHyphenationFrequency(hyphenationFrequency)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
builder.setJustificationMode(justificationMode)
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
builder.setUseLineSpacingFromFallbacks(true)
}
layout = builder.build()
}
return layout
}
// Return text alignment according to LTR or RTL style
private val _textAlign: Int
get() {
var textAlign = super.textAlign
if (layoutDirection == YogaDirection.RTL) {
if (textAlign == Gravity.RIGHT) {
textAlign = Gravity.LEFT
} else if (textAlign == Gravity.LEFT) {
textAlign = Gravity.RIGHT
}
}
return textAlign
}
override fun onBeforeLayout(nativeViewHierarchyOptimizer: NativeViewHierarchyOptimizer) {
preparedSpannableText =
spannedFromShadowNode(
this, /* text (e.g. from `value` prop): */
null, /* supportsInlineViews: */
true,
nativeViewHierarchyOptimizer,
)
markUpdated()
}
// Text's descendants aren't necessarily all virtual nodes. Text can contain a combination
// of
// virtual and non-virtual (e.g. inline views) nodes. Therefore it's not a virtual anchor
// by the doc comment on [ReactShadowNode.isVirtualAnchor].
override fun isVirtualAnchor(): Boolean = false
override fun hoistNativeChildren(): Boolean = true
override fun markUpdated() {
super.markUpdated()
// Telling to Yoga that the node should be remeasured on next layout pass.
super.dirty()
error(
"ReactTextShadowNode methods are unsupported, and the ShadowNode will be fully removed in a future version of React Native."
)
}
@Suppress("UNUSED_PARAMETER")
override fun onBeforeLayout(nativeViewHierarchyOptimizer: NativeViewHierarchyOptimizer) {
error(
"ReactTextShadowNode methods are unsupported, and the ShadowNode will be fully removed in a future version of React Native."
)
}
@Suppress("UNUSED_PARAMETER")
override fun onCollectExtraUpdates(uiViewOperationQueue: UIViewOperationQueue) {
super.onCollectExtraUpdates(uiViewOperationQueue)
val text = preparedSpannableText ?: return
val reactTextUpdate =
ReactTextUpdate(
text,
ReactConstants.UNSET,
containsImages,
getPadding(Spacing.START),
getPadding(Spacing.TOP),
getPadding(Spacing.END),
getPadding(Spacing.BOTTOM),
_textAlign,
textBreakStrategy,
justificationMode,
)
uiViewOperationQueue.enqueueUpdateExtraData(reactTag, reactTextUpdate)
error(
"ReactTextShadowNode methods are unsupported, and the ShadowNode will be fully removed in a future version of React Native."
)
}
@Suppress("UNUSED_PARAMETER")
@ReactProp(name = "onTextLayout")
public fun setShouldNotifyOnTextLayout(shouldNotifyOnTextLayout: Boolean) {
this.shouldNotifyOnTextLayout = shouldNotifyOnTextLayout
error(
"ReactTextShadowNode methods are unsupported, and the ShadowNode will be fully removed in a future version of React Native."
)
}
override fun calculateLayoutOnChildren(): Iterable<ReactShadowNode<*>?>? {
// Run flexbox on and return the descendants which are inline views.
if (inlineViews.isNullOrEmpty()) {
return null
}
val text: Spanned =
checkNotNull(preparedSpannableText) {
"Spannable element has not been prepared in onBeforeLayout"
}
val placeholders = text.getSpans(0, text.length, TextInlineViewPlaceholderSpan::class.java)
val shadowNodes = mutableListOf<ReactShadowNode<*>?>()
for (placeholder in placeholders) {
val child = inlineViews?.get(placeholder.reactTag)
checkNotNull(child) { "Child is null" }
child.calculateLayout()
shadowNodes.add(child)
}
return shadowNodes
}
private companion object {
// It's important to pass the ANTI_ALIAS_FLAG flag to the constructor rather than setting it
// later by calling setFlags. This is because the latter approach triggers a bug on Android
// 4.4.2.
// The bug is that unicode emoticons aren't measured properly which causes text to be
// clipped.
private val textPaintInstance = TextPaint(TextPaint.ANTI_ALIAS_FLAG)
error(
"ReactTextShadowNode methods are unsupported, and the ShadowNode will be fully removed in a future version of React Native."
)
}
}
@@ -9,32 +9,17 @@
package com.facebook.react.views.textinput
import android.annotation.SuppressLint
import android.text.Layout
import android.util.TypedValue
import android.view.ViewGroup
import android.widget.EditText
import androidx.appcompat.view.ContextThemeWrapper
import androidx.core.view.ViewCompat
import com.facebook.common.logging.FLog
import com.facebook.infer.annotation.Assertions
import com.facebook.react.R
import com.facebook.react.common.ReactConstants
import com.facebook.react.common.annotations.LegacyArchitectureShadowNodeWithCxxImpl
import com.facebook.react.common.annotations.internal.LegacyArchitecture
import com.facebook.react.common.annotations.internal.LegacyArchitectureLogLevel
import com.facebook.react.common.annotations.internal.LegacyArchitectureLogger
import com.facebook.react.uimanager.Spacing
import com.facebook.react.uimanager.ThemedReactContext
import com.facebook.react.uimanager.UIViewOperationQueue
import com.facebook.react.uimanager.annotations.ReactProp
import com.facebook.react.views.text.ReactBaseTextShadowNode
import com.facebook.react.views.text.ReactTextUpdate
import com.facebook.react.views.text.ReactTextViewManagerCallback
import com.facebook.react.views.view.MeasureUtil.getMeasureSpec
import com.facebook.yoga.YogaMeasureFunction
import com.facebook.yoga.YogaMeasureMode
import com.facebook.yoga.YogaMeasureOutput
import com.facebook.yoga.YogaNode
@LegacyArchitecture(logLevel = LegacyArchitectureLogLevel.ERROR)
@@ -47,62 +32,33 @@ internal class ReactTextInputShadowNode
@JvmOverloads
constructor(reactTextViewManagerCallback: ReactTextViewManagerCallback? = null) :
ReactBaseTextShadowNode(reactTextViewManagerCallback), YogaMeasureFunction {
private var mostRecentEventCount = ReactConstants.UNSET
private var internalEditText: EditText? = null
private var localData: ReactTextInputLocalData? = null
// Represents the `text` property only, not possible nested content.
@Suppress("UNUSED_PARAMETER")
@set:ReactProp(name = PROP_TEXT)
var text: String? = null
set(value) {
field = value
markUpdated()
set(_) {
error(
"ReactTextInputShadowNode methods are unsupported, and the ShadowNode will be fully removed in a future version of React Native."
)
}
@Suppress("UNUSED_PARAMETER")
@set:ReactProp(name = PROP_PLACEHOLDER)
var placeholder: String? = null
set(value) {
field = value
markUpdated()
set(_) {
error(
"ReactTextInputShadowNode methods are unsupported, and the ShadowNode will be fully removed in a future version of React Native."
)
}
init {
textBreakStrategy = Layout.BREAK_STRATEGY_HIGH_QUALITY
setMeasureFunction(this)
}
@Suppress("DEPRECATION")
@Suppress("UNUSED_PARAMETER")
override fun setThemedContext(themedContext: ThemedReactContext) {
super.setThemedContext(themedContext)
// [EditText] has by default a border at the bottom of its view
// called "underline". To have a native look and feel of the TextEdit
// we have to preserve it at least by default.
// The border (underline) has its padding set by the background image
// provided by the system (which vary a lot among versions and vendors
// of Android), and it cannot be changed.
// So, we have to enforce it as a default padding.
// TODO #7120264: Cache this stuff better.
val editText = createInternalEditText()
setDefaultPadding(Spacing.START, ViewCompat.getPaddingStart(editText).toFloat())
setDefaultPadding(Spacing.TOP, editText.paddingTop.toFloat())
setDefaultPadding(Spacing.END, ViewCompat.getPaddingEnd(editText).toFloat())
setDefaultPadding(Spacing.BOTTOM, editText.paddingBottom.toFloat())
internalEditText = editText
// We must measure the EditText without paddings, so we have to reset them.
internalEditText?.setPadding(0, 0, 0, 0)
// This is needed to fix an android bug since 4.4.3 which will throw an NPE in measure,
// setting the layoutParams fixes it: https://code.google.com/p/android/issues/detail?id=75877
internalEditText?.layoutParams =
ViewGroup.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT,
)
error(
"ReactTextInputShadowNode methods are unsupported, and the ShadowNode will be fully removed in a future version of React Native."
)
}
@Suppress("UNUSED_PARAMETER")
override fun measure(
node: YogaNode,
width: Float,
@@ -110,107 +66,57 @@ constructor(reactTextViewManagerCallback: ReactTextViewManagerCallback? = null)
height: Float,
heightMode: YogaMeasureMode,
): Long {
// measure() should never be called before setThemedContext()
val editText = checkNotNull(internalEditText)
if (localData != null) {
localData?.apply(editText)
} else {
editText.setTextSize(TypedValue.COMPLEX_UNIT_PX, textAttributes.effectiveFontSize.toFloat())
if (numberOfLines != ReactConstants.UNSET) {
editText.setLines(numberOfLines)
}
@SuppressLint("WrongConstant")
if (editText.breakStrategy != textBreakStrategy) {
editText.breakStrategy = textBreakStrategy
}
}
// make sure the placeholder content is also being measured
editText.hint = placeholder
editText.measure(getMeasureSpec(width, widthMode), getMeasureSpec(height, heightMode))
return YogaMeasureOutput.make(editText.measuredWidth, editText.measuredHeight)
error(
"ReactTextInputShadowNode methods are unsupported, and the ShadowNode will be fully removed in a future version of React Native."
)
}
override fun isVirtualAnchor(): Boolean = true
override fun isVirtualAnchor(): Boolean {
error(
"ReactTextInputShadowNode methods are unsupported, and the ShadowNode will be fully removed in a future version of React Native."
)
}
override fun isYogaLeafNode(): Boolean = true
override fun isYogaLeafNode(): Boolean {
error(
"ReactTextInputShadowNode methods are unsupported, and the ShadowNode will be fully removed in a future version of React Native."
)
}
@Suppress("UNUSED_PARAMETER")
override fun setLocalData(data: Any) {
Assertions.assertCondition(data is ReactTextInputLocalData)
localData = data as ReactTextInputLocalData
// Telling to Yoga that the node should be remeasured on next layout pass.
dirty()
// Note: We should NOT mark the node updated (by calling {@code markUpdated}) here
// because the state remains the same.
error(
"ReactTextInputShadowNode methods are unsupported, and the ShadowNode will be fully removed in a future version of React Native."
)
}
@Suppress("UNUSED_PARAMETER")
@ReactProp(name = "mostRecentEventCount")
public fun setMostRecentEventCount(mostRecentEventCount: Int) {
this.mostRecentEventCount = mostRecentEventCount
error(
"ReactTextInputShadowNode methods are unsupported, and the ShadowNode will be fully removed in a future version of React Native."
)
}
@Suppress("UNUSED_PARAMETER")
override fun setTextBreakStrategy(textBreakStrategy: String?) {
when (textBreakStrategy) {
null,
"simple" -> this.textBreakStrategy = Layout.BREAK_STRATEGY_SIMPLE
"highQuality" -> this.textBreakStrategy = Layout.BREAK_STRATEGY_HIGH_QUALITY
"balanced" -> this.textBreakStrategy = Layout.BREAK_STRATEGY_BALANCED
else -> {
FLog.w(ReactConstants.TAG, "Invalid textBreakStrategy: $textBreakStrategy")
this.textBreakStrategy = Layout.BREAK_STRATEGY_SIMPLE
}
}
error(
"ReactTextInputShadowNode methods are unsupported, and the ShadowNode will be fully removed in a future version of React Native."
)
}
@Suppress("UNUSED_PARAMETER")
override fun onCollectExtraUpdates(uiViewOperationQueue: UIViewOperationQueue) {
super.onCollectExtraUpdates(uiViewOperationQueue)
if (mostRecentEventCount != ReactConstants.UNSET) {
val reactTextUpdate =
ReactTextUpdate(
spannedFromShadowNode(
this,
text, /* supportsInlineViews: */
false, /* nativeViewHierarchyOptimizer: */
null, // only needed to support inline views
),
mostRecentEventCount,
containsImages,
getPadding(Spacing.LEFT),
getPadding(Spacing.TOP),
getPadding(Spacing.RIGHT),
getPadding(Spacing.BOTTOM),
textAlign,
textBreakStrategy,
justificationMode,
)
uiViewOperationQueue.enqueueUpdateExtraData(reactTag, reactTextUpdate)
}
error(
"ReactTextInputShadowNode methods are unsupported, and the ShadowNode will be fully removed in a future version of React Native."
)
}
@Suppress("UNUSED_PARAMETER")
override fun setPadding(spacingType: Int, padding: Float) {
super.setPadding(spacingType, padding)
markUpdated()
}
/**
* May be overridden by subclasses that would like to provide their own instance of the internal
* `EditText` this class uses to determine the expected size of the view.
*/
private fun createInternalEditText(): EditText {
// By setting a style which has a background drawable, this EditText will have a different
// background drawable instance from that on the UI Thread, which maybe has a default background
// drawable instance.
// Otherwise, DrawableContainer is not a thread safe class, and it caused the npe in #29452.
val context =
ContextThemeWrapper(themedContext, R.style.Theme_ReactNative_TextInput_DefaultBackground)
return EditText(context)
error(
"ReactTextInputShadowNode methods are unsupported, and the ShadowNode will be fully removed in a future version of React Native."
)
}
companion object {