From db5c52de8bd222ef78e358f3525dccc27863e2f2 Mon Sep 17 00:00:00 2001 From: Tomek Zawadzki Date: Wed, 21 Oct 2026 11:40:25 -0700 Subject: [PATCH] Re-land "Keep paragraph content and measured layouts across unchanged clones" (#59285) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Summary: Re-land of https://github.com/react/react-native/issues/59063, which was reverted in ad2f4519195 because it broke `textAdjustsDynamicLayout` on Android. This PR has four commits: the Android fix for that regression, https://github.com/react/react-native/issues/59063 unchanged, fixes for the two prepared-layout cache concerns raised in the revert, and a fix for a crash in https://github.com/react/react-native/issues/59063 that I found while measuring memory. **https://github.com/react/react-native/issues/59063 (unchanged).** A `ParagraphShadowNode` cloned without new props or children (e.g. by Yoga, because a sibling changed) keeps its attributed string and measured layouts. Unchanged siblings then get no state update and no re-layout. On a Galaxy A16, changing one of 1000 labels takes 66% less time to pixels than on current `main` (benchmarks at the end). **1. Why `textAdjustsDynamicLayout` broke, and the fix (`ReactTextView`).** `ReactTextView` fits `adjustsFontSizeToFit` text by shrinking the font size spans of its Spannable in place. When the view grows, `onSizeChanged` schedules another fit, but that fit starts from the largest span it finds, which is the already-shrunk size. The text can shrink further but never grow back. It only grew back when a state update happened to deliver a new Spannable with the original sizes. https://github.com/react/react-native/issues/59063 removed the spurious state update the example relied on, so the text stayed small after the container grew. This is also a bug on `main` today, just one that depends on order: in RNTester, *Set Height to 60 → 20 → 40* right after opening the example leaves the text small at 40, because no state update lands on that last resize. With this change, the view keeps the font size spans the text had before the first fit and restores them, along with the paint's base text size, before each new fit. **2. Carried content is validated before its layouts are used.** `measureContent` looked up a carried layout before `getContent` checked that the carried content was built for the current font size multiplier and layout direction. With `enablePreparedTextLayout`, a font scale change while the app is running reused layouts measured at the old scale, so text was drawn at the new size into boxes measured at the old one and was cut off. The check now runs first. **3. Equal measured sizes don't imply equal layouts.** `findUsableLayout` matches a layout by its measured size. Text with `adjustsFontSizeToFit` can measure the same under different constraints with a different font size, so its prepared layouts are no longer carried across revisions. When several layouts of the same size exist, the one measured for the current revision is preferred over carried ones. **4. Prepared layouts no longer pile up across revisions (crash fix).** https://github.com/react/react-native/issues/59063 copied every prepared layout of the source into the clone, and new measurements were added to them, so when only the constraints kept changing (e.g. a container being resized while its texts stay the same) the layouts accumulated across revisions. Each one holds a JNI global reference on Android, and with `enablePreparedTextLayout` the app aborted with *JNI ERROR: global reference table overflow* after about 20 resizes of a container with 300 texts. Now `layout()` keeps only the layout it used and a clone carries at most that one, so a paragraph holds one carried layout plus those measured in its own revision. ## Changelog: [GENERAL] [FIXED] - Avoid state updates and re-layout of unchanged `Text` siblings when a sibling changes [ANDROID] [FIXED] - `adjustsFontSizeToFit` text grows back when its container grows Pull Request resolved: https://github.com/react/react-native/pull/59285 Test Plan: - `./gradlew :packages:react-native:ReactAndroid:testDebugUnitTest --tests "com.facebook.react.views.text.*"`: 94 tests pass. The new `adjustsFontSizeToFitGrowsBackWhenContainerHeightGrows` fails without the `ReactTextView` change (font size stays at 4 instead of 40). - `yarn format-check-java`, `format-check-kotlin` and `format-check-cpp` pass on the changed files. - RNTester `textAdjustsDynamicLayout`, release build on an Android emulator: | steps | `main` | https://github.com/react/react-native/issues/59063 alone | this PR | |---|---|---|---| | open → 40 | grows | stays small | grows | | open → 60 → 20 → 40 | stays small | stays small | grows | - Live changes compared pixel by pixel with a fresh remount of the same state, using a local RNTester screen (not part of this PR) with an `adjustsFontSizeToFit` text, mixed LTR/RTL texts, nested spans and a counter. Release builds; Android on a Galaxy A16, iOS on an iPhone Air simulator (iOS 26.5). ✓ = identical to the remount. | live change | Android default | Android `enablePreparedTextLayout` | iOS | |---|---|---|---| | container height 20 → 40 → 60 → 20 → 40 (`adjustsFontSizeToFit`) | ✓ (https://github.com/react/react-native/issues/59063 alone: ✗) | ✓ | ✓ | | `direction` LTR → RTL → LTR on the parent | ✓ | ✓ | ✓ | | update one sibling's text | ✓ | ✓ | ✓ | | font scale 1.0 → 1.3 → 1.0 / Dynamic Type L → XXL → L | ✓ | ✓ (https://github.com/react/react-native/issues/59063 alone: ✗, text clipped) | ✓ | | density 450 → 360 → 450 dpi, `fixTextLayoutOnPixelDensityChange` on | ✓ | ✓ | n/a | - Text with inline views (Text examples → *Inline views*, including the RTL ones), both Android text paths: four live font scale changes, no crash, text reflows correctly. - Not run: Fantom (the bundled `nlohmann/json.hpp` doesn't build with this machine's Apple clang, so I'm relying on CI), and a physical iPhone. **Benchmarks.** Samsung Galaxy A16, RNTester release builds of current `main` (c7429b0e97b) and this PR, with a text benchmark screen that is not part of this PR. The two builds alternated round by round; medians of 12 runs (4 rounds × 3 runs after a warm-up run), battery 27.6–27.9 °C. | changing one item, right after mount | `main` | this PR | change | |---|--:|--:|--:| | 1000 labels: time to pixels | 225 ms | 77 ms | −66% | | 1000 labels: UI-thread CPU | 178 ms | 38 ms | −79% | | 1000 labels, `enablePreparedTextLayout`: time to pixels | 250 ms | 74 ms | −70% | | 1000 labels, `enablePreparedTextLayout`: JS-thread CPU | 153 ms | 41 ms | −74% | | 300 strings: time to pixels | 149 ms | 36 ms | −76% | | 300 strings: UI-thread CPU | 139 ms | 35 ms | −75% | | 100-post feed: time to pixels | 95 ms | 88 ms | −7% | Mounts: time to pixels is unchanged (−2% to +4%, within run-to-run noise). With `enablePreparedTextLayout`, mounting 1000 labels uses about 10 ms more JS-thread CPU and about 40 ms more total CPU (+9%) in every round, probably from copying the prepared layouts into clones, without a change in time to pixels. Two earlier rounds were left out: in them both builds produced many extra frames per update, probably because Android Studio's screen mirroring was attached to the phone at the time. This PR was still faster in those rounds (1000 labels: 164 ms vs 2406 ms). **Prepared layouts per update** (1000 labels, `enablePreparedTextLayout`, counted with a temporary log in `measureContent`): changing one label prepares 1001 layouts on `main` (every sibling) and 1 with this PR. The fourth commit doesn't change this. **Memory.** Android emulator (Pixel 10 Pro AVD, API 37), release builds, `dumpsys meminfo` total PSS 10 s after the sequence with the tree still mounted, medians of 3 runs: | sequence | `main` | this PR | change | |---|--:|--:|--:| | 1000 labels, 20 single-label updates | 117.5 MB | 110.1 MB | −6% | | same, `enablePreparedTextLayout` | 136.4 MB | 109.2 MB | −20% (Java heap 23.3 → 9.1 MB) | | 300 labels, container resized 120 times (40 widths) | 101.7 MB | 94.6 MB | −7% | | same, `enablePreparedTextLayout` | 120.1 MB | 121.0 MB | +1% | | same, 400 resizes, `enablePreparedTextLayout` | 143.7 MB | 144.3 MB | +0% | Without the fourth commit, the prepared resize sequences crashed (see 4. above). The live-change comparisons, the `textAdjustsDynamicLayout` table and the Galaxy A16 benchmarks above were run before the fourth commit, which changes only which prepared layouts a clone keeps; the layout counts and memory numbers include it. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Reviewed By: christophpurrer Differential Revision: D126622505 Pulled By: javache fbshipit-source-id: 490447c113263f4335ffc7ff4ffc540751518a6a --- .../react/views/text/ReactTextView.java | 32 +++++++ .../react/views/text/ReactTextViewTest.kt | 40 ++++++++ .../components/text/ParagraphShadowNode.cpp | 96 +++++++++++++++++-- .../components/text/ParagraphShadowNode.h | 14 ++- 4 files changed, 170 insertions(+), 12 deletions(-) diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/text/ReactTextView.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/text/ReactTextView.java index 18321fa94e8..451677c8d1f 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/text/ReactTextView.java +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/text/ReactTextView.java @@ -52,6 +52,7 @@ import com.facebook.react.uimanager.style.LogicalEdge; import com.facebook.react.uimanager.style.Overflow; import com.facebook.react.util.AndroidVersion; import com.facebook.react.views.text.internal.span.CanvasEffectSpan; +import com.facebook.react.views.text.internal.span.ReactAbsoluteSizeSpan; import com.facebook.react.views.text.internal.span.ReactFragmentIndexSpan; import com.facebook.react.views.text.internal.span.ReactTagSpan; import com.facebook.yoga.YogaMeasureMode; @@ -84,6 +85,11 @@ public class ReactTextView extends AppCompatTextView implements ReactCompoundVie private Overflow mOverflow = Overflow.VISIBLE; private @Nullable Spannable mSpanned; + // Fitting the font size to the view shrinks the font size spans of mSpanned in place. These are + // the spans it had before the first fit, so that a later fit (when the view's size changes) can + // start from the original sizes, and the text can grow back. + private @Nullable Spanned mUnfittedSpanned; + private @Nullable TextAttributeProps mBaseTextAttributes; private @Nullable PreparedLayout mPreparedLayout; @SuppressWarnings("this-escape") @@ -143,6 +149,8 @@ public class ReactTextView extends AppCompatTextView implements ReactCompoundVie mLetterSpacing = 0.f; mOverflow = Overflow.VISIBLE; mSpanned = null; + mUnfittedSpanned = null; + mBaseTextAttributes = null; mPreparedLayout = null; matchLineBreakingToMeasurement(); } @@ -246,6 +254,13 @@ public class ReactTextView extends AppCompatTextView implements ReactCompoundVie Spannable spanned = getSpanned(); if (mAdjustsFontSizeToFit && spanned != null && mShouldAdjustSpannableFontSize) { mShouldAdjustSpannableFontSize = false; + if (mUnfittedSpanned == null) { + mUnfittedSpanned = new SpannableString(spanned); + } else { + restoreUnfittedFontSizes(spanned, mUnfittedSpanned); + // Fitting also scales the paint's text size, so start again from the base attributes. + applyBaseTextAttributes(mBaseTextAttributes); + } TextLayoutManager.adjustSpannableFontToFit( spanned, getWidth(), @@ -419,11 +434,27 @@ public class ReactTextView extends AppCompatTextView implements ReactCompoundVie } } + private static void restoreUnfittedFontSizes(Spannable spanned, Spanned unfitted) { + for (ReactAbsoluteSizeSpan span : + spanned.getSpans(0, spanned.length(), ReactAbsoluteSizeSpan.class)) { + spanned.removeSpan(span); + } + for (ReactAbsoluteSizeSpan span : + unfitted.getSpans(0, unfitted.length(), ReactAbsoluteSizeSpan.class)) { + spanned.setSpan( + span, + unfitted.getSpanStart(span), + unfitted.getSpanEnd(span), + unfitted.getSpanFlags(span)); + } + } + /** * Android draws generated ellipses with the view's paint rather than a span, so it must match the * base attributes TextLayoutManager measured with. */ private void applyBaseTextAttributes(@Nullable TextAttributeProps baseTextAttributes) { + mBaseTextAttributes = baseTextAttributes; if (baseTextAttributes == null) { return; } @@ -699,6 +730,7 @@ public class ReactTextView extends AppCompatTextView implements ReactCompoundVie public void setSpanned(Spannable spanned) { mSpanned = spanned; + mUnfittedSpanned = null; mShouldAdjustSpannableFontSize = true; } diff --git a/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/views/text/ReactTextViewTest.kt b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/views/text/ReactTextViewTest.kt index 21d03ca2d4f..1ddd04fb2aa 100644 --- a/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/views/text/ReactTextViewTest.kt +++ b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/views/text/ReactTextViewTest.kt @@ -185,6 +185,46 @@ class ReactTextViewTest { assertThat(fontSizeWhenShort).isLessThan(fontSizeWhenTall) } + @Test + fun adjustsFontSizeToFitGrowsBackWhenContainerHeightGrows() { + val width = 200 + val tallHeight = 200 + val shortHeight = 20 + val largeFontSize = 40 + + val text = SpannableString("Hello") + text.setSpan( + ReactAbsoluteSizeSpan(largeFontSize), + 0, + text.length, + Spanned.SPAN_EXCLUSIVE_EXCLUSIVE, + ) + + val view = TestReactTextView(RuntimeEnvironment.getApplication()) + view.layoutParams = + ViewGroup.LayoutParams( + ViewGroup.LayoutParams.WRAP_CONTENT, + ViewGroup.LayoutParams.WRAP_CONTENT, + ) + view.setTextColor(Color.BLACK) + view.setMinimumFontScale(0.1f) + view.setNumberOfLines(0) + view.setAdjustFontSizeToFit(true) + view.setSpanned(text) + view.text = text + + layoutAndDraw(view, width, shortHeight) + val fontSizeWhenShort = largestAbsoluteSizeSpan(text) + + // Growing the container without a new text update must fit the text again starting from its + // original font size, not from the size it was already shrunk to. + layoutAndDraw(view, width, tallHeight) + val fontSizeWhenTall = largestAbsoluteSizeSpan(text) + + assertThat(fontSizeWhenShort).isLessThan(largeFontSize) + assertThat(fontSizeWhenTall).isEqualTo(largeFontSize) + } + @Test @Config(sdk = [35]) fun breaksLinesOnAdvancesLikeMeasurementOnApi35() { diff --git a/packages/react-native/ReactCommon/react/renderer/components/text/ParagraphShadowNode.cpp b/packages/react-native/ReactCommon/react/renderer/components/text/ParagraphShadowNode.cpp index 9009071df8d..8dca3bade3e 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/text/ParagraphShadowNode.cpp +++ b/packages/react-native/ReactCommon/react/renderer/components/text/ParagraphShadowNode.cpp @@ -59,6 +59,35 @@ ParagraphShadowNode::ParagraphShadowNode( const ShadowNodeFragment& fragment) : ConcreteViewShadowNode(sourceShadowNode, fragment) { initialize(); + // A revision with neither new props nor new children (e.g. one Yoga cloned + // because a sibling changed) renders the same content, so keep the + // attributed string and the layouts measured for it instead of rebuilding + // and re-measuring them. `getContent` drops both if the layout context they + // were built for no longer matches. + // + // Content with attachments is not kept: they point at the children the + // content was built from, and `layout` replaces those children with laid-out + // clones, so in a later revision the pointers would outlive the nodes. + if (fragment.props == nullptr && fragment.children == nullptr) { + const auto& source = + static_cast(sourceShadowNode); + if (source.content_.has_value() && source.content_->attachments.empty()) { + content_ = source.content_; + // A layout is later matched by its measured size alone (see + // `findUsableLayout`). Text that fits its font size to the constraints + // can measure the same under different constraints with a different + // font size, so its layouts are not kept. + // + // Only the layout the source used is kept (`layout` drops the others). + // Every layout holds a JNI global reference on Android, so carrying all + // of them would let them pile up across revisions when only the + // constraints change, until the global reference table overflows. + if (!source.content_->paragraphAttributes.adjustsFontSizeToFit && + !source.measuredLayouts_.empty()) { + measuredLayouts_.push_back(source.measuredLayouts_.back()); + } + } + } } bool ParagraphShadowNode::shouldNewRevisionDirtyMeasurement( @@ -67,8 +96,36 @@ bool ParagraphShadowNode::shouldNewRevisionDirtyMeasurement( return fragment.props != nullptr; } +LayoutDirection ParagraphShadowNode::resolvedLayoutDirection() const { + return YGNodeLayoutGetDirection(&yogaNode_) == YGDirectionRTL + ? LayoutDirection::RightToLeft + : LayoutDirection::LeftToRight; +} + +void ParagraphShadowNode::dropContentBuiltForAnotherContext( + const LayoutContext& layoutContext) const { + if (!content_.has_value()) { + return; + } + const auto& baseTextAttributes = + content_->attributedString.getBaseTextAttributes(); + // The content is built from this node's props and children, and it is only + // carried over to revisions that have neither new props nor new children + // (see the copy constructor). The only other inputs are the font size + // multiplier from the layout context and the layout direction Yoga resolves + // from the parent, and those can change without new props or children, so + // they are the two things to check here. + if (baseTextAttributes.fontSizeMultiplier != + layoutContext.fontSizeMultiplier || + baseTextAttributes.layoutDirection != resolvedLayoutDirection()) { + content_.reset(); + measuredLayouts_.clear(); + } +} + const Content& ParagraphShadowNode::getContent( const LayoutContext& layoutContext) const { + dropContentBuiltForAnotherContext(layoutContext); if (content_.has_value()) { return content_.value(); } @@ -78,10 +135,7 @@ const Content& ParagraphShadowNode::getContent( auto textAttributes = TextAttributes::defaultTextAttributes(); textAttributes.fontSizeMultiplier = layoutContext.fontSizeMultiplier; textAttributes.apply(getConcreteProps().textAttributes); - textAttributes.layoutDirection = - YGNodeLayoutGetDirection(&yogaNode_) == YGDirectionRTL - ? LayoutDirection::RightToLeft - : LayoutDirection::LeftToRight; + textAttributes.layoutDirection = resolvedLayoutDirection(); auto attributedString = AttributedString{}; auto attachments = Attachments{}; buildAttributedString(textAttributes, *this, attributedString, attachments); @@ -204,7 +258,8 @@ void ParagraphShadowNode::updateStateIfNeeded(const Content& content) { #endif } -MeasuredPreparedTextLayout* ParagraphShadowNode::findUsableLayout() { +MeasuredPreparedTextLayout* ParagraphShadowNode::findUsableLayout( + Float pointScaleFactor) { MeasuredPreparedTextLayout* ret = nullptr; if constexpr (TextLayoutManagerExtended::supportsPreparedTextLayout()) { @@ -215,8 +270,13 @@ MeasuredPreparedTextLayout* ParagraphShadowNode::findUsableLayout() { // exact width/height was given), or if our content measurement was // adjusted by a constraint (like min-size). auto expectedSize = rawContentSize(); - for (auto& prevLayout : measuredLayouts_) { - if (floatEquality( + // Newest first, so that a layout measured for this revision wins over an + // equally sized one carried over from a previous revision. + for (auto it = measuredLayouts_.rbegin(); it != measuredLayouts_.rend(); + ++it) { + auto& prevLayout = *it; + if (prevLayout.pointScaleFactor == pointScaleFactor && + floatEquality( prevLayout.measurement.size.width, expectedSize.width) && floatEquality( prevLayout.measurement.size.height, expectedSize.height)) { @@ -244,9 +304,16 @@ Size ParagraphShadowNode::rawContentSize() { Size ParagraphShadowNode::measureContent( const LayoutContext& layoutContext, const LayoutConstraints& layoutConstraints) const { + // Layouts carried over from a previous revision were prepared for its + // content, so drop them first if that content no longer applies. + dropContentBuiltForAnotherContext(layoutContext); + if constexpr (TextLayoutManagerExtended::supportsPreparedTextLayout()) { + // Layouts carried over from a previous revision may have been prepared + // at another pixel density, which they can't be reused for. for (const auto& layout : measuredLayouts_) { - if (layout.layoutConstraints == layoutConstraints) { + if (layout.layoutConstraints == layoutConstraints && + layout.pointScaleFactor == layoutContext.pointScaleFactor) { return layout.measurement.size; } } @@ -336,7 +403,7 @@ void ParagraphShadowNode::layout(LayoutContext layoutContext) { auto content = getContentWithMeasuredAttachments(layoutContext, layoutConstraints); - auto measuredLayout = findUsableLayout(); + auto measuredLayout = findUsableLayout(layoutContext.pointScaleFactor); if constexpr ( TextLayoutManagerExtended::supportsPreparedTextLayout() && @@ -353,11 +420,20 @@ void ParagraphShadowNode::layout(LayoutContext layoutContext) { // culled if (measuredLayout == nullptr) { measureContent(layoutContext, layoutConstraints); - measuredLayout = findUsableLayout(); + measuredLayout = findUsableLayout(layoutContext.pointScaleFactor); } react_native_assert(measuredLayout); updateStateIfNeeded(content, *measuredLayout); + // Only this layout can be reused by a later revision (see the copy + // constructor), so drop the others measured for this one. + if (measuredLayouts_.size() > 1) { + auto usedLayout = std::move(*measuredLayout); + measuredLayouts_.clear(); + measuredLayouts_.push_back(std::move(usedLayout)); + measuredLayout = &measuredLayouts_.back(); + } + } else if (ReactNativeFeatureFlags::fixTextLayoutOnPixelDensityChange()) { MeasuredPreparedTextLayout unpreparedLayout; unpreparedLayout.pointScaleFactor = layoutContext.pointScaleFactor; diff --git a/packages/react-native/ReactCommon/react/renderer/components/text/ParagraphShadowNode.h b/packages/react-native/ReactCommon/react/renderer/components/text/ParagraphShadowNode.h index f569067717b..1e4f3b0a805 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/text/ParagraphShadowNode.h +++ b/packages/react-native/ReactCommon/react/renderer/components/text/ParagraphShadowNode.h @@ -95,6 +95,15 @@ class ParagraphShadowNode */ const Content &getContent(const LayoutContext &layoutContext) const; + /* + * Drops the content and the layouts measured for it if the content was built + * for another font size multiplier or layout direction (it may have been + * carried over from a previous revision). + */ + void dropContentBuiltForAnotherContext(const LayoutContext &layoutContext) const; + + LayoutDirection resolvedLayoutDirection() const; + /* * Builds and returns a `Content` object with given `layoutConstraints`. */ @@ -117,9 +126,10 @@ class ParagraphShadowNode /** * Returns any previously prepared layout, generated for measurement, which - * may be used, given the currently assigned layout to the ShadowNode + * may be used, given the currently assigned layout to the ShadowNode and + * the current pixel density */ - MeasuredPreparedTextLayout *findUsableLayout(); + MeasuredPreparedTextLayout *findUsableLayout(Float pointScaleFactor); /** * Returns the final measure of the content frame, before layout rounding