Skip to content

Commit f45900a

Browse files
authored
Support inline views in Text with lineHeight on Android (#59833)
Summary: Fixes the issue described in [#48727](#48727) on Android, where adding inline views and images into Text when line height is specified results in the image clipping and overflowing the parent container. ### Root Cause On Android, CustomLineHeightSpan uses the line's merged font metrics `fm` to set the line's ascent/descent so text clamps to `lineHeight`. However, the calculation assumes `fm` only describes text whereas in reality, it also includes the height of inline views/images. As a result, taller images are also clamped to `lineHeight` and overflow. Additionally, because `StaticLayout` seeds each line with the previous line's adjusted font metrics when a text run wraps, the lines after the inline view also inherit its height and get misplaced baselines. The result is that wrapped text following an inline image appear unusually squashed. ### This PR For Android, modify CustomLineHeightSpan so that if the text includes an inline view, we use `TextPaint` to re-derive `fm` via `measureTextFontMetrics()` for every line. This means `fm` only describes text during the `chooseHeight()` calculation, so each line is unaffected by wrapping issues. Then, raise the line's ascent/top to fit the inline view. All changes are gated behind the `fixTextInlineViewLineHeight` flag. Changelog: [Android][Fixed] - Inline views in Text with lineHeight no longer overflow the text Differential Revision: D130190408 Pull Request resolved: #59833
1 parent f03f09f commit f45900a

3 files changed

Lines changed: 421 additions & 18 deletions

File tree

‎packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/text/TextLayoutManager.kt‎

Lines changed: 34 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,7 @@ import com.facebook.react.util.AndroidVersion.VERSION_CODE_VANILLA_ICE_CREAM
4747
import com.facebook.react.views.text.internal.span.CustomLetterSpacingSpan
4848
import com.facebook.react.views.text.internal.span.CustomLineHeightSpan
4949
import com.facebook.react.views.text.internal.span.CustomStyleSpan
50+
import com.facebook.react.views.text.internal.span.InlineViewHeights
5051
import com.facebook.react.views.text.internal.span.ReactAbsoluteSizeSpan
5152
import com.facebook.react.views.text.internal.span.ReactBackgroundColorSpan
5253
import com.facebook.react.views.text.internal.span.ReactClickableSpan
@@ -313,6 +314,17 @@ internal object TextLayoutManager {
313314
// single spans, avoiding duplicate draws (e.g. multiple accent marks in HighlighterTextSpan).
314315
var pendingEffects: List<TextAttributeProps.TextEffectEntry> = emptyList()
315316
var pendingEffectStart = 0
317+
val inlineViews by
318+
lazy(LazyThreadSafetyMode.NONE) {
319+
val hasInlineViews =
320+
ReactNativeFeatureFlags.fixTextInlineViewLineHeight() &&
321+
(0 until fragments.count).any { i ->
322+
val fragment = fragments.getMapBuffer(i)
323+
fragment.contains(FR_KEY_IS_ATTACHMENT) &&
324+
fragment.getBoolean(FR_KEY_IS_ATTACHMENT)
325+
}
326+
if (hasInlineViews) InlineViewHeights() else null
327+
}
316328

317329
for (i in 0 until fragments.count) {
318330
val fragment = fragments.getMapBuffer(i)
@@ -442,7 +454,13 @@ internal object TextLayoutManager {
442454
)
443455
}
444456
if (!textAttributes.lineHeight.isNaN()) {
445-
ops.add(SetSpanOperation(start, end, CustomLineHeightSpan(textAttributes.lineHeight)))
457+
ops.add(
458+
SetSpanOperation(
459+
start,
460+
end,
461+
CustomLineHeightSpan(textAttributes.lineHeight, inlineViews),
462+
),
463+
)
446464
}
447465

448466
if (ReactNativeFeatureFlags.enablePreparedTextLayout()) {
@@ -540,6 +558,15 @@ internal object TextLayoutManager {
540558
}
541559

542560
val spannable = SpannableString(text)
561+
val inlineViews =
562+
if (
563+
ReactNativeFeatureFlags.fixTextInlineViewLineHeight() &&
564+
parsedFragments.any { it.isAttachment }
565+
) {
566+
InlineViewHeights()
567+
} else {
568+
null
569+
}
543570

544571
// Track pending text effects to coalesce consecutive fragments with the same effects into
545572
// single spans, avoiding duplicate draws (e.g. multiple accent marks in HighlighterTextSpan).
@@ -679,7 +706,12 @@ internal object TextLayoutManager {
679706
}
680707

681708
if (!fragment.props.lineHeight.isNaN()) {
682-
spannable.setSpan(CustomLineHeightSpan(fragment.props.lineHeight), start, end, spanFlags)
709+
spannable.setSpan(
710+
CustomLineHeightSpan(fragment.props.lineHeight, inlineViews),
711+
start,
712+
end,
713+
spanFlags,
714+
)
683715
}
684716

685717
if (ReactNativeFeatureFlags.enablePreparedTextLayout()) {

‎packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/text/internal/span/CustomLineHeightSpan.kt‎

Lines changed: 137 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,16 +8,26 @@
88
package com.facebook.react.views.text.internal.span
99

1010
import android.graphics.Paint.FontMetricsInt
11+
import android.text.Spanned
12+
import android.text.TextPaint
1113
import android.text.style.LineHeightSpan
14+
import android.text.style.MetricAffectingSpan
1215
import kotlin.math.ceil
1316
import kotlin.math.floor
17+
import kotlin.math.max
1418

1519
/**
1620
* Implements a [LineHeightSpan] which follows web-like behavior for line height, unlike
1721
* LineHeightSpan.Standard which only effects space between the baselines of adjacent line boxes
1822
* (does not impact space before the first line or after the last).
23+
*
24+
* Pass [inlineViews] when the text contains a [TextInlineViewPlaceholderSpan], so that lines
25+
* holding an inline view grow to contain it, as CSS does for inline replaced elements.
1926
*/
20-
internal class CustomLineHeightSpan(height: Float) : LineHeightSpan, ReactSpan {
27+
internal class CustomLineHeightSpan(
28+
height: Float,
29+
private val inlineViews: InlineViewHeights? = null,
30+
) : LineHeightSpan.WithDensity, ReactSpan {
2131
val lineHeight: Int = ceil(height.toDouble()).toInt()
2232

2333
override fun chooseHeight(
@@ -53,4 +63,130 @@ internal class CustomLineHeightSpan(height: Float) : LineHeightSpan, ReactSpan {
5363
fm.bottom = fm.descent
5464
}
5565
}
66+
67+
override fun chooseHeight(
68+
text: CharSequence,
69+
start: Int,
70+
end: Int,
71+
spanstartv: Int,
72+
v: Int,
73+
fm: FontMetricsInt,
74+
paint: TextPaint,
75+
) {
76+
if (inlineViews == null || text !is Spanned) {
77+
chooseHeight(text, start, end, spanstartv, v, fm)
78+
return
79+
}
80+
81+
// If text contains an inline view anywhere, remeasure fm before calling chooseHeight() to avoid
82+
// clipping the view. StaticLayout seeds the next line's fm with this line's if a text run
83+
// wraps, so remeasurement is needed even if an inline view doesn't exist on the current line.
84+
//
85+
// Metrics on a line without an inline view that already add up to the line height need no
86+
// remeasurement: an earlier span set them for this line, or StaticLayout seeded them from a
87+
// previous line that ended at the line height.
88+
val inlineViewHeight = inlineViews.maxHeight(text, start, end)
89+
if (inlineViewHeight == 0 && -fm.ascent + fm.descent == lineHeight) {
90+
chooseHeight(text, start, end, spanstartv, v, fm)
91+
return
92+
}
93+
measureTextFontMetrics(text, start, end, paint, fm)
94+
chooseHeight(text, start, end, spanstartv, v, fm)
95+
if (inlineViewHeight > 0) {
96+
fm.ascent = minOf(fm.ascent, -inlineViewHeight)
97+
fm.descent = maxOf(fm.descent, 0)
98+
fm.top = minOf(fm.top, fm.ascent)
99+
fm.bottom = maxOf(fm.bottom, fm.descent)
100+
}
101+
}
102+
103+
/**
104+
* Sets [fm] to the combined font metrics of the text in [start, end), excluding inline views.
105+
*
106+
* The line is split into runs at each [MetricAffectingSpan] transition. Each run that is not an
107+
* inline view placeholder is measured with [basePaint] after applying that run's spans (font
108+
* size, typeface, etc.), and [fm] encloses the tallest ascent and deepest descent across runs. If
109+
* the line has no text runs (only inline views), [fm] falls back to the metrics of [basePaint],
110+
* matching the strut of a CSS line box.
111+
*
112+
* Only the primary font of each run is measured, so unlike StaticLayout, glyphs drawn with a
113+
* fallback font (such as emoji) do not contribute to the metrics.
114+
*/
115+
private fun measureTextFontMetrics(
116+
text: Spanned,
117+
start: Int,
118+
end: Int,
119+
basePaint: TextPaint,
120+
fm: FontMetricsInt,
121+
) {
122+
val runPaint = textPaintInstance.get()!!
123+
val runFm = fontMetricsInstance.get()!!
124+
fm.top = 0
125+
fm.ascent = 0
126+
fm.descent = 0
127+
fm.bottom = 0
128+
var hasTextRun = false
129+
var runStart = start
130+
while (runStart < end) {
131+
val runEnd = text.nextSpanTransition(runStart, end, MetricAffectingSpan::class.java)
132+
if (text.getSpans(runStart, runEnd, TextInlineViewPlaceholderSpan::class.java).isEmpty()) {
133+
hasTextRun = true
134+
runPaint.set(basePaint)
135+
text.getSpans(runStart, runEnd, MetricAffectingSpan::class.java).forEach {
136+
it.updateMeasureState(runPaint)
137+
}
138+
runPaint.getFontMetricsInt(runFm)
139+
fm.top = minOf(fm.top, runFm.top)
140+
fm.ascent = minOf(fm.ascent, runFm.ascent)
141+
fm.descent = maxOf(fm.descent, runFm.descent)
142+
fm.bottom = maxOf(fm.bottom, runFm.bottom)
143+
}
144+
runStart = runEnd
145+
}
146+
if (!hasTextRun) {
147+
basePaint.getFontMetricsInt(fm)
148+
}
149+
}
150+
151+
private companion object {
152+
private val textPaintInstance: ThreadLocal<TextPaint> =
153+
object : ThreadLocal<TextPaint>() {
154+
override fun initialValue(): TextPaint = TextPaint()
155+
}
156+
157+
private val fontMetricsInstance: ThreadLocal<FontMetricsInt> =
158+
object : ThreadLocal<FontMetricsInt>() {
159+
override fun initialValue(): FontMetricsInt = FontMetricsInt()
160+
}
161+
}
162+
}
163+
164+
/**
165+
* The inline views of one text, shared by all of its [CustomLineHeightSpan]s so that the text is
166+
* scanned for them once rather than once per span per line.
167+
*/
168+
internal class InlineViewHeights {
169+
private class Entries(val starts: IntArray, val ends: IntArray, val heights: IntArray)
170+
171+
@Volatile private var entries: Entries? = null
172+
173+
fun maxHeight(text: Spanned, start: Int, end: Int): Int {
174+
val entries = this.entries ?: load(text).also { this.entries = it }
175+
var height = 0
176+
for (i in entries.starts.indices) {
177+
if (entries.starts[i] < end && entries.ends[i] > start) {
178+
height = max(height, entries.heights[i])
179+
}
180+
}
181+
return height
182+
}
183+
184+
private fun load(text: Spanned): Entries {
185+
val spans = text.getSpans(0, text.length, TextInlineViewPlaceholderSpan::class.java)
186+
return Entries(
187+
starts = IntArray(spans.size) { text.getSpanStart(spans[it]) },
188+
ends = IntArray(spans.size) { text.getSpanEnd(spans[it]) },
189+
heights = IntArray(spans.size) { spans[it].height },
190+
)
191+
}
56192
}

0 commit comments

Comments
 (0)