Skip to content

Commit 63c3b8e

Browse files
Abbondanzogabrieldonadel
authored andcommitted
Keep whole-pixel text widths from wrapping on Android (#59791) (#59791)
(cherry picked from commit 225e8aa)
1 parent b3b5a68 commit 63c3b8e

3 files changed

Lines changed: 138 additions & 4 deletions

File tree

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

Lines changed: 18 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,10 @@ internal object TextLayoutManager {
118118

119119
private const val TEXT_WIDTH_MODE_LONGEST_LINE = "longest-line"
120120

121+
// Widths arrive in pixels converted from Yoga's floating point DIPs, so a width of a whole number
122+
// of pixels can arrive a fraction of a pixel short of it (e.g. 371.99997 instead of 372).
123+
private const val PIXEL_WIDTH_TOLERANCE = 0.001f
124+
121125
private val tagToSpannableCache = ConcurrentHashMap<Int, Spannable>()
122126

123127
// These wrappers mirror Android 15 APIs but use reflection because some internal targets still
@@ -865,7 +869,8 @@ internal object TextLayoutManager {
865869
// layout as a BoringLayout
866870
if (
867871
boring != null &&
868-
(widthYogaMeasureMode == YogaMeasureMode.UNDEFINED || boring.width <= floor(width))
872+
(widthYogaMeasureMode == YogaMeasureMode.UNDEFINED ||
873+
boring.width <= floorPixelWidth(width))
869874
) {
870875
// Guard uses floor() but layout width below uses ceil() for EXACTLY mode intentionally:
871876
// text that barely fails the floor-based guard falls through to StaticLayout, which also
@@ -888,15 +893,16 @@ internal object TextLayoutManager {
888893
// Layout.getDesiredWidth is a full measuring pass over the text, so only run it when its
889894
// result can affect the layout width. It cannot when the width is EXACTLY, nor when the text
890895
// was boring but did not fit: boring.width is the unwrapped width of the same text and we only
891-
// get here if it exceeds floor(width), so min(desiredWidth, floor(width)) is floor(width).
896+
// get here if it exceeds the floored width, so the minimum of both is the floored width.
892897
val layoutWidth =
893898
when {
894899
widthYogaMeasureMode == YogaMeasureMode.EXACTLY -> ceil(width).toInt()
895-
widthYogaMeasureMode == YogaMeasureMode.AT_MOST && boring != null -> floor(width).toInt()
900+
widthYogaMeasureMode == YogaMeasureMode.AT_MOST && boring != null ->
901+
floorPixelWidth(width)
896902
else -> {
897903
val desiredWidth = ceil(Layout.getDesiredWidth(text, paint)).toInt()
898904
if (widthYogaMeasureMode == YogaMeasureMode.AT_MOST) {
899-
min(desiredWidth, floor(width).toInt())
905+
min(desiredWidth, floorPixelWidth(width))
900906
} else {
901907
desiredWidth
902908
}
@@ -970,6 +976,14 @@ internal object TextLayoutManager {
970976
}
971977
}
972978

979+
/**
980+
* Rounds a maximum width down to whole pixels, without losing the last pixel of a width that
981+
* falls a floating point error short of it. Text measured at a whole number of pixels gets that
982+
* width back as its constraint once Yoga has converted it to DIPs and back, and flooring that to
983+
* one pixel less wraps the text.
984+
*/
985+
private fun floorPixelWidth(width: Float): Int = floor(width + PIXEL_WIDTH_TOLERANCE).toInt()
986+
973987
@VisibleForTesting
974988
internal fun adjustLayoutForRtlRightOverhang(
975989
layout: Layout,
Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
/*
2+
* Copyright (c) Meta Platforms, Inc. and affiliates.
3+
*
4+
* This source code is licensed under the MIT license found in the
5+
* LICENSE file in the root directory of this source tree.
6+
*/
7+
8+
package com.facebook.react.views.text
9+
10+
import android.annotation.SuppressLint
11+
import android.graphics.text.LineBreakConfig
12+
import android.text.BoringLayout
13+
import android.text.Layout
14+
import android.text.SpannableString
15+
import android.text.TextPaint
16+
import com.facebook.yoga.YogaMeasureMode
17+
import kotlin.math.ceil
18+
import org.assertj.core.api.Assertions.assertThat
19+
import org.junit.Test
20+
import org.junit.runner.RunWith
21+
import org.robolectric.RobolectricTestRunner
22+
import org.robolectric.annotation.GraphicsMode
23+
import org.robolectric.annotation.TextLayoutMode
24+
25+
@RunWith(RobolectricTestRunner::class)
26+
@GraphicsMode(GraphicsMode.Mode.NATIVE)
27+
@TextLayoutMode(TextLayoutMode.Mode.REALISTIC)
28+
class TextLayoutManagerPixelWidthTest {
29+
private val text = SpannableString("Add payment method")
30+
private val paint = TextPaint(TextPaint.ANTI_ALIAS_FLAG).apply { textSize = 16f }
31+
private val measuredWidth = ceil(Layout.getDesiredWidth(text, paint)).toInt()
32+
33+
@Test
34+
fun `AT_MOST width a floating point error short of the measured width keeps one line`() {
35+
val widths = listOf(Math.nextDown(measuredWidth.toFloat()), measuredWidth - 0.0004f)
36+
for (width in widths) {
37+
for (boring in listOf(BoringLayout.isBoring(text, paint), null)) {
38+
val layout = createLayout(width, boring)
39+
40+
assertThat(layout.width).isEqualTo(measuredWidth)
41+
assertThat(layout.lineCount).isEqualTo(1)
42+
}
43+
}
44+
}
45+
46+
@Test
47+
fun `AT_MOST width a fraction of a pixel short of the measured width wraps`() {
48+
for (boring in listOf(BoringLayout.isBoring(text, paint), null)) {
49+
val layout = createLayout(measuredWidth - 0.5f, boring)
50+
51+
assertThat(layout.width).isEqualTo(measuredWidth - 1)
52+
assertThat(layout.lineCount).isGreaterThan(1)
53+
}
54+
}
55+
56+
@SuppressLint("InlinedApi")
57+
private fun createLayout(width: Float, boring: BoringLayout.Metrics?): Layout =
58+
TextLayoutManager.createLayout(
59+
text,
60+
boring,
61+
width,
62+
YogaMeasureMode.AT_MOST,
63+
/* includeFontPadding = */ false,
64+
/* textBreakStrategy = */ Layout.BREAK_STRATEGY_HIGH_QUALITY,
65+
/* hyphenationFrequency = */ Layout.HYPHENATION_FREQUENCY_NONE,
66+
/* lineBreakStyle = */ LineBreakConfig.LINE_BREAK_STYLE_NONE,
67+
/* lineBreakWordStyle = */ LineBreakConfig.LINE_BREAK_WORD_STYLE_NONE,
68+
Layout.Alignment.ALIGN_NORMAL,
69+
/* justificationMode = */ 0,
70+
/* ellipsizeMode = */ null,
71+
/* maxNumberOfLines = */ 0,
72+
paint,
73+
)
74+
}

‎packages/rn-tester/js/examples/Text/TextExample.android.js‎

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ const React = require('react');
2424
const {
2525
Image,
2626
LayoutAnimation,
27+
PixelRatio,
2728
StyleSheet,
2829
Text,
2930
TextInput,
@@ -1388,6 +1389,32 @@ function TextBaseLineLayoutExample(props: {}): React.Node {
13881389
);
13891390
}
13901391

1392+
function FitContentWholePixelWidthExample(props: {}): React.Node {
1393+
// Each label is measured, then measured again with its own width as its
1394+
// maximum, because its container is only as wide as the label and the
1395+
// container's padding. That maximum picks up floating point error from the
1396+
// padding and from the conversion to DIPs and back, so it can fall a hair
1397+
// short of the label's width. Each row is about a pixel wider than the last.
1398+
// No label should wrap.
1399+
const rows = [];
1400+
for (let i = 0; i < 17; i++) {
1401+
rows.push(
1402+
<View key={i} style={styles.fitContentRow}>
1403+
<View style={styles.fitContentLabelContainer}>
1404+
<Text
1405+
style={[
1406+
styles.fitContentLabel,
1407+
{letterSpacing: -0.25 + i / (18 * PixelRatio.get())},
1408+
]}>
1409+
Add payment method
1410+
</Text>
1411+
</View>
1412+
</View>,
1413+
);
1414+
}
1415+
return <View testID="text-fit-content-whole-pixel-width">{rows}</View>;
1416+
}
1417+
13911418
const examples = [
13921419
{
13931420
title: 'Wrapped text width mode',
@@ -1484,6 +1511,11 @@ const examples = [
14841511
);
14851512
},
14861513
},
1514+
{
1515+
title: 'Fit-content text at whole pixel widths',
1516+
name: 'fitContentWholePixelWidth',
1517+
render: FitContentWholePixelWidthExample,
1518+
},
14871519
{
14881520
title: 'Hyphenation',
14891521
name: 'hyphenation',
@@ -1982,6 +2014,20 @@ const styles = StyleSheet.create({
19822014
wrappedText: {
19832015
maxWidth: 300,
19842016
},
2017+
fitContentRow: {
2018+
backgroundColor: '#E4E6EB',
2019+
flexDirection: 'row',
2020+
justifyContent: 'center',
2021+
marginBottom: 2,
2022+
},
2023+
fitContentLabelContainer: {
2024+
alignItems: 'center',
2025+
paddingHorizontal: 60.15,
2026+
},
2027+
fitContentLabel: {
2028+
fontSize: 15,
2029+
maxWidth: '100%',
2030+
},
19852031
lineBreakSample: {
19862032
backgroundColor: '#eee',
19872033
fontSize: 16,

0 commit comments

Comments
 (0)