From bd323929dc5be5666ee36043babec7d981a095dc Mon Sep 17 00:00:00 2001 From: Jakub Piasecki Date: Sat, 21 Sep 2024 06:34:21 -0700 Subject: [PATCH] Add a workaround for text being measured incorrectly when ending with an empty line (#42331) Summary: It looks like `StaticLayout` used for measuring multiline text on the new architecture returns wrong metrics for the last line if it's empty, however, if it contains anything, then the returned values are correct. Similar approach with measuring `I` was already used in `ReactEditText`: https://github.com/facebook/react-native/blob/258d8e51b451b221e557dad4647cbd210fe37392/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/textinput/ReactEditText.java#L1203-L1213 ## Changelog: [ANDROID] [FIXED] - Fixed text being measured incorrectly when ending with an empty line on the new architecture Pull Request resolved: https://github.com/facebook/react-native/pull/42331 Test Plan:
I tested the change on this simple code on React Native 0.73.2 (with the new arch enabled) ```jsx import React from 'react'; import {useState} from 'react'; import {SafeAreaView, TextInput} from 'react-native'; export default function App() { const [text, setText] = useState('ABC\nDEF\nGHI\n'); return ( ); } ```
Before: https://github.com/facebook/react-native/assets/21055725/0787cc86-70c6-4238-b93a-87984e527a83 After: https://github.com/facebook/react-native/assets/21055725/2acf619f-5cb4-4869-9576-cb8cc081c15b Reviewed By: cipolleschi Differential Revision: D62873674 Pulled By: cortinico fbshipit-source-id: cc2481b1924a13af7326cfc16c59b9390f0d06d8 --- .../com/facebook/react/views/text/TextLayoutManager.java | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/text/TextLayoutManager.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/text/TextLayoutManager.java index 706b77825eb..03303089ca3 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/text/TextLayoutManager.java +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/text/TextLayoutManager.java @@ -355,6 +355,15 @@ public class TextLayoutManager { int hyphenationFrequency, Layout.Alignment alignment) { Layout layout; + // StaticLayout returns wrong metrics for the last line if it's empty, add something to the + // last line so it's measured correctly + if (text.toString().endsWith("\n")) { + SpannableStringBuilder sb = new SpannableStringBuilder(text); + sb.append("I"); + + text = sb; + } + int spanLength = text.length(); boolean unconstrainedWidth = widthYogaMeasureMode == YogaMeasureMode.UNDEFINED || width < 0; float desiredWidth =