Skip to content

Commit db5c52d

Browse files
tomekzawmeta-codesync[bot]
authored andcommitted
Re-land "Keep paragraph content and measured layouts across unchanged clones" (#59285)
Summary: Re-land of #59063, which was reverted in ad2f451 because it broke `textAdjustsDynamicLayout` on Android. This PR has four commits: the Android fix for that regression, #59063 unchanged, fixes for the two prepared-layout cache concerns raised in the revert, and a fix for a crash in #59063 that I found while measuring memory. **#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. #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).** #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: #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` | #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`) | ✓ (#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 | ✓ | ✓ (#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` (c7429b0) 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
1 parent 6b27a28 commit db5c52d

4 files changed

Lines changed: 170 additions & 12 deletions

File tree

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

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,7 @@
5252
import com.facebook.react.uimanager.style.Overflow;
5353
import com.facebook.react.util.AndroidVersion;
5454
import com.facebook.react.views.text.internal.span.CanvasEffectSpan;
55+
import com.facebook.react.views.text.internal.span.ReactAbsoluteSizeSpan;
5556
import com.facebook.react.views.text.internal.span.ReactFragmentIndexSpan;
5657
import com.facebook.react.views.text.internal.span.ReactTagSpan;
5758
import com.facebook.yoga.YogaMeasureMode;
@@ -84,6 +85,11 @@ public class ReactTextView extends AppCompatTextView implements ReactCompoundVie
8485
private Overflow mOverflow = Overflow.VISIBLE;
8586

8687
private @Nullable Spannable mSpanned;
88+
// Fitting the font size to the view shrinks the font size spans of mSpanned in place. These are
89+
// the spans it had before the first fit, so that a later fit (when the view's size changes) can
90+
// start from the original sizes, and the text can grow back.
91+
private @Nullable Spanned mUnfittedSpanned;
92+
private @Nullable TextAttributeProps mBaseTextAttributes;
8793
private @Nullable PreparedLayout mPreparedLayout;
8894

8995
@SuppressWarnings("this-escape")
@@ -143,6 +149,8 @@ private void initView() {
143149
mLetterSpacing = 0.f;
144150
mOverflow = Overflow.VISIBLE;
145151
mSpanned = null;
152+
mUnfittedSpanned = null;
153+
mBaseTextAttributes = null;
146154
mPreparedLayout = null;
147155
matchLineBreakingToMeasurement();
148156
}
@@ -246,6 +254,13 @@ protected void onDraw(Canvas canvas) {
246254
Spannable spanned = getSpanned();
247255
if (mAdjustsFontSizeToFit && spanned != null && mShouldAdjustSpannableFontSize) {
248256
mShouldAdjustSpannableFontSize = false;
257+
if (mUnfittedSpanned == null) {
258+
mUnfittedSpanned = new SpannableString(spanned);
259+
} else {
260+
restoreUnfittedFontSizes(spanned, mUnfittedSpanned);
261+
// Fitting also scales the paint's text size, so start again from the base attributes.
262+
applyBaseTextAttributes(mBaseTextAttributes);
263+
}
249264
TextLayoutManager.adjustSpannableFontToFit(
250265
spanned,
251266
getWidth(),
@@ -419,11 +434,27 @@ public void setText(ReactTextUpdate update) {
419434
}
420435
}
421436

437+
private static void restoreUnfittedFontSizes(Spannable spanned, Spanned unfitted) {
438+
for (ReactAbsoluteSizeSpan span :
439+
spanned.getSpans(0, spanned.length(), ReactAbsoluteSizeSpan.class)) {
440+
spanned.removeSpan(span);
441+
}
442+
for (ReactAbsoluteSizeSpan span :
443+
unfitted.getSpans(0, unfitted.length(), ReactAbsoluteSizeSpan.class)) {
444+
spanned.setSpan(
445+
span,
446+
unfitted.getSpanStart(span),
447+
unfitted.getSpanEnd(span),
448+
unfitted.getSpanFlags(span));
449+
}
450+
}
451+
422452
/**
423453
* Android draws generated ellipses with the view's paint rather than a span, so it must match the
424454
* base attributes TextLayoutManager measured with.
425455
*/
426456
private void applyBaseTextAttributes(@Nullable TextAttributeProps baseTextAttributes) {
457+
mBaseTextAttributes = baseTextAttributes;
427458
if (baseTextAttributes == null) {
428459
return;
429460
}
@@ -699,6 +730,7 @@ public void setBorderStyle(@Nullable String style) {
699730

700731
public void setSpanned(Spannable spanned) {
701732
mSpanned = spanned;
733+
mUnfittedSpanned = null;
702734
mShouldAdjustSpannableFontSize = true;
703735
}
704736

‎packages/react-native/ReactAndroid/src/test/java/com/facebook/react/views/text/ReactTextViewTest.kt‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -185,6 +185,46 @@ class ReactTextViewTest {
185185
assertThat(fontSizeWhenShort).isLessThan(fontSizeWhenTall)
186186
}
187187

188+
@Test
189+
fun adjustsFontSizeToFitGrowsBackWhenContainerHeightGrows() {
190+
val width = 200
191+
val tallHeight = 200
192+
val shortHeight = 20
193+
val largeFontSize = 40
194+
195+
val text = SpannableString("Hello")
196+
text.setSpan(
197+
ReactAbsoluteSizeSpan(largeFontSize),
198+
0,
199+
text.length,
200+
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE,
201+
)
202+
203+
val view = TestReactTextView(RuntimeEnvironment.getApplication())
204+
view.layoutParams =
205+
ViewGroup.LayoutParams(
206+
ViewGroup.LayoutParams.WRAP_CONTENT,
207+
ViewGroup.LayoutParams.WRAP_CONTENT,
208+
)
209+
view.setTextColor(Color.BLACK)
210+
view.setMinimumFontScale(0.1f)
211+
view.setNumberOfLines(0)
212+
view.setAdjustFontSizeToFit(true)
213+
view.setSpanned(text)
214+
view.text = text
215+
216+
layoutAndDraw(view, width, shortHeight)
217+
val fontSizeWhenShort = largestAbsoluteSizeSpan(text)
218+
219+
// Growing the container without a new text update must fit the text again starting from its
220+
// original font size, not from the size it was already shrunk to.
221+
layoutAndDraw(view, width, tallHeight)
222+
val fontSizeWhenTall = largestAbsoluteSizeSpan(text)
223+
224+
assertThat(fontSizeWhenShort).isLessThan(largeFontSize)
225+
assertThat(fontSizeWhenTall).isEqualTo(largeFontSize)
226+
}
227+
188228
@Test
189229
@Config(sdk = [35])
190230
fun breaksLinesOnAdvancesLikeMeasurementOnApi35() {

‎packages/react-native/ReactCommon/react/renderer/components/text/ParagraphShadowNode.cpp‎

Lines changed: 86 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,35 @@ ParagraphShadowNode::ParagraphShadowNode(
5959
const ShadowNodeFragment& fragment)
6060
: ConcreteViewShadowNode(sourceShadowNode, fragment) {
6161
initialize();
62+
// A revision with neither new props nor new children (e.g. one Yoga cloned
63+
// because a sibling changed) renders the same content, so keep the
64+
// attributed string and the layouts measured for it instead of rebuilding
65+
// and re-measuring them. `getContent` drops both if the layout context they
66+
// were built for no longer matches.
67+
//
68+
// Content with attachments is not kept: they point at the children the
69+
// content was built from, and `layout` replaces those children with laid-out
70+
// clones, so in a later revision the pointers would outlive the nodes.
71+
if (fragment.props == nullptr && fragment.children == nullptr) {
72+
const auto& source =
73+
static_cast<const ParagraphShadowNode&>(sourceShadowNode);
74+
if (source.content_.has_value() && source.content_->attachments.empty()) {
75+
content_ = source.content_;
76+
// A layout is later matched by its measured size alone (see
77+
// `findUsableLayout`). Text that fits its font size to the constraints
78+
// can measure the same under different constraints with a different
79+
// font size, so its layouts are not kept.
80+
//
81+
// Only the layout the source used is kept (`layout` drops the others).
82+
// Every layout holds a JNI global reference on Android, so carrying all
83+
// of them would let them pile up across revisions when only the
84+
// constraints change, until the global reference table overflows.
85+
if (!source.content_->paragraphAttributes.adjustsFontSizeToFit &&
86+
!source.measuredLayouts_.empty()) {
87+
measuredLayouts_.push_back(source.measuredLayouts_.back());
88+
}
89+
}
90+
}
6291
}
6392

6493
bool ParagraphShadowNode::shouldNewRevisionDirtyMeasurement(
@@ -67,8 +96,36 @@ bool ParagraphShadowNode::shouldNewRevisionDirtyMeasurement(
6796
return fragment.props != nullptr;
6897
}
6998

99+
LayoutDirection ParagraphShadowNode::resolvedLayoutDirection() const {
100+
return YGNodeLayoutGetDirection(&yogaNode_) == YGDirectionRTL
101+
? LayoutDirection::RightToLeft
102+
: LayoutDirection::LeftToRight;
103+
}
104+
105+
void ParagraphShadowNode::dropContentBuiltForAnotherContext(
106+
const LayoutContext& layoutContext) const {
107+
if (!content_.has_value()) {
108+
return;
109+
}
110+
const auto& baseTextAttributes =
111+
content_->attributedString.getBaseTextAttributes();
112+
// The content is built from this node's props and children, and it is only
113+
// carried over to revisions that have neither new props nor new children
114+
// (see the copy constructor). The only other inputs are the font size
115+
// multiplier from the layout context and the layout direction Yoga resolves
116+
// from the parent, and those can change without new props or children, so
117+
// they are the two things to check here.
118+
if (baseTextAttributes.fontSizeMultiplier !=
119+
layoutContext.fontSizeMultiplier ||
120+
baseTextAttributes.layoutDirection != resolvedLayoutDirection()) {
121+
content_.reset();
122+
measuredLayouts_.clear();
123+
}
124+
}
125+
70126
const Content& ParagraphShadowNode::getContent(
71127
const LayoutContext& layoutContext) const {
128+
dropContentBuiltForAnotherContext(layoutContext);
72129
if (content_.has_value()) {
73130
return content_.value();
74131
}
@@ -78,10 +135,7 @@ const Content& ParagraphShadowNode::getContent(
78135
auto textAttributes = TextAttributes::defaultTextAttributes();
79136
textAttributes.fontSizeMultiplier = layoutContext.fontSizeMultiplier;
80137
textAttributes.apply(getConcreteProps().textAttributes);
81-
textAttributes.layoutDirection =
82-
YGNodeLayoutGetDirection(&yogaNode_) == YGDirectionRTL
83-
? LayoutDirection::RightToLeft
84-
: LayoutDirection::LeftToRight;
138+
textAttributes.layoutDirection = resolvedLayoutDirection();
85139
auto attributedString = AttributedString{};
86140
auto attachments = Attachments{};
87141
buildAttributedString(textAttributes, *this, attributedString, attachments);
@@ -204,7 +258,8 @@ void ParagraphShadowNode::updateStateIfNeeded(const Content& content) {
204258
#endif
205259
}
206260

207-
MeasuredPreparedTextLayout* ParagraphShadowNode::findUsableLayout() {
261+
MeasuredPreparedTextLayout* ParagraphShadowNode::findUsableLayout(
262+
Float pointScaleFactor) {
208263
MeasuredPreparedTextLayout* ret = nullptr;
209264

210265
if constexpr (TextLayoutManagerExtended::supportsPreparedTextLayout()) {
@@ -215,8 +270,13 @@ MeasuredPreparedTextLayout* ParagraphShadowNode::findUsableLayout() {
215270
// exact width/height was given), or if our content measurement was
216271
// adjusted by a constraint (like min-size).
217272
auto expectedSize = rawContentSize();
218-
for (auto& prevLayout : measuredLayouts_) {
219-
if (floatEquality(
273+
// Newest first, so that a layout measured for this revision wins over an
274+
// equally sized one carried over from a previous revision.
275+
for (auto it = measuredLayouts_.rbegin(); it != measuredLayouts_.rend();
276+
++it) {
277+
auto& prevLayout = *it;
278+
if (prevLayout.pointScaleFactor == pointScaleFactor &&
279+
floatEquality(
220280
prevLayout.measurement.size.width, expectedSize.width) &&
221281
floatEquality(
222282
prevLayout.measurement.size.height, expectedSize.height)) {
@@ -244,9 +304,16 @@ Size ParagraphShadowNode::rawContentSize() {
244304
Size ParagraphShadowNode::measureContent(
245305
const LayoutContext& layoutContext,
246306
const LayoutConstraints& layoutConstraints) const {
307+
// Layouts carried over from a previous revision were prepared for its
308+
// content, so drop them first if that content no longer applies.
309+
dropContentBuiltForAnotherContext(layoutContext);
310+
247311
if constexpr (TextLayoutManagerExtended::supportsPreparedTextLayout()) {
312+
// Layouts carried over from a previous revision may have been prepared
313+
// at another pixel density, which they can't be reused for.
248314
for (const auto& layout : measuredLayouts_) {
249-
if (layout.layoutConstraints == layoutConstraints) {
315+
if (layout.layoutConstraints == layoutConstraints &&
316+
layout.pointScaleFactor == layoutContext.pointScaleFactor) {
250317
return layout.measurement.size;
251318
}
252319
}
@@ -336,7 +403,7 @@ void ParagraphShadowNode::layout(LayoutContext layoutContext) {
336403
auto content =
337404
getContentWithMeasuredAttachments(layoutContext, layoutConstraints);
338405

339-
auto measuredLayout = findUsableLayout();
406+
auto measuredLayout = findUsableLayout(layoutContext.pointScaleFactor);
340407

341408
if constexpr (
342409
TextLayoutManagerExtended::supportsPreparedTextLayout() &&
@@ -353,11 +420,20 @@ void ParagraphShadowNode::layout(LayoutContext layoutContext) {
353420
// culled
354421
if (measuredLayout == nullptr) {
355422
measureContent(layoutContext, layoutConstraints);
356-
measuredLayout = findUsableLayout();
423+
measuredLayout = findUsableLayout(layoutContext.pointScaleFactor);
357424
}
358425
react_native_assert(measuredLayout);
359426
updateStateIfNeeded<ParagraphState>(content, *measuredLayout);
360427

428+
// Only this layout can be reused by a later revision (see the copy
429+
// constructor), so drop the others measured for this one.
430+
if (measuredLayouts_.size() > 1) {
431+
auto usedLayout = std::move(*measuredLayout);
432+
measuredLayouts_.clear();
433+
measuredLayouts_.push_back(std::move(usedLayout));
434+
measuredLayout = &measuredLayouts_.back();
435+
}
436+
361437
} else if (ReactNativeFeatureFlags::fixTextLayoutOnPixelDensityChange()) {
362438
MeasuredPreparedTextLayout unpreparedLayout;
363439
unpreparedLayout.pointScaleFactor = layoutContext.pointScaleFactor;

‎packages/react-native/ReactCommon/react/renderer/components/text/ParagraphShadowNode.h‎

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,15 @@ class ParagraphShadowNode
9595
*/
9696
const Content &getContent(const LayoutContext &layoutContext) const;
9797

98+
/*
99+
* Drops the content and the layouts measured for it if the content was built
100+
* for another font size multiplier or layout direction (it may have been
101+
* carried over from a previous revision).
102+
*/
103+
void dropContentBuiltForAnotherContext(const LayoutContext &layoutContext) const;
104+
105+
LayoutDirection resolvedLayoutDirection() const;
106+
98107
/*
99108
* Builds and returns a `Content` object with given `layoutConstraints`.
100109
*/
@@ -117,9 +126,10 @@ class ParagraphShadowNode
117126

118127
/**
119128
* Returns any previously prepared layout, generated for measurement, which
120-
* may be used, given the currently assigned layout to the ShadowNode
129+
* may be used, given the currently assigned layout to the ShadowNode and
130+
* the current pixel density
121131
*/
122-
MeasuredPreparedTextLayout *findUsableLayout();
132+
MeasuredPreparedTextLayout *findUsableLayout(Float pointScaleFactor);
123133

124134
/**
125135
* Returns the final measure of the content frame, before layout rounding

0 commit comments

Comments
 (0)