Skip to content

Commit 480fe97

Browse files
authored
Find a Text's clickable spans only when a touch needs them
## Summary: `PreparedLayoutTextView` collects the `ClickableSpan`s of its text every time its prepared layout changes, which is every time the text is updated: it walks the text with `nextSpanTransition`, calls `getSpans` for each segment and copies the results into a list. The list itself is never read. Touch handling only checks whether it is empty before hit testing a tap, and focus handling only checks it before clearing the selection. With this change, touch handling checks whether the text has a `ClickableSpan` on its first touch after a layout change, with a single `getSpans`, and keeps the answer until the next layout change. Losing focus clears the selection when there is one, which is the state it resets, instead of looking at the spans. Texts that are never touched no longer pay for the scan. This is the main thread work done for every update of a `Text` whose spannable has spans, so it adds up on screens where many texts change often (lists of messages, prices, scores, counters). ## Changelog: [ANDROID] [CHANGED] - Find the clickable spans of a Text only when it is touched, instead of on every text update ## Test Plan: - New `PreparedLayoutTextViewClickableSpanTest`: tapping a `ClickableSpan` clicks it; after the text is replaced by one without clickable spans a tap no longer clicks; after the text is replaced by one with a clickable span a tap clicks it. `./gradlew :packages:react-native:ReactAndroid:testDebugUnitTest --tests 'com.facebook.react.views.text.*'` passes (104 tests). - `yarn format-check-kotlin` reports no changes. - **On a device.** Two RNTester release APKs built from the same local checkout (with local benchmark screens, and `PreparedLayoutTextView.kt` identical to `main` at 9bc1a28), without and with this change, installed alternately on a moto g57 power (Android 16). Each install first opens a screen with a static text containing a nested `<Text onPress>` link and taps the link: `onPress` fired once on every install of both builds (10 installs). Then a Playground screen of 200 rich text rows (bold, colored, italic and a link per row) where every row changes every 100 ms runs for 30 s, and the main and JS thread CPU time is read from `/proc`: | | before | this PR | change | |---|--:|--:|--:| | Main thread, 30 s | 4.88 / 5.01 s | 4.61 / 4.64 s | −6.5% | | JS thread, 30 s | 15.00 / 14.66 s | 14.67 / 14.69 s | no change | Three earlier rounds, with a build that differed only in the focus check (which this screen never runs), gave the same result: main thread 4.97 / 5.15 / 4.93 s before and 4.68 / 4.65 / 4.70 s after (−6.8%). In a simpleperf profile of the same screen before this change, collecting the spans (`nextSpanTransition`, `getSpans` and the list copies in the `preparedLayout` setter, called from `PreparedLayoutTextViewManager.updateExtraData`) was about 5% of the main thread. - Not covered by a unit test: the focus change path, which now checks `selection != null` (the selection is private). 🤖 Generated with [Claude Code](https://claude.com/claude-code) Differential Revision: D128363239 Pull Request resolved: #59583
1 parent 04c6ea4 commit 480fe97

2 files changed

Lines changed: 156 additions & 21 deletions

File tree

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

Lines changed: 15 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,9 @@ import kotlin.math.roundToInt
4848
@DoNotStrip
4949
internal class PreparedLayoutTextView(context: Context) : ViewGroup(context), ReactCompoundView {
5050

51-
private var clickableSpans: List<ClickableSpan> = emptyList()
51+
// Whether the text has a ClickableSpan. Only touch handling needs it, so it is found on first use
52+
// rather than on every text update; null until then.
53+
private var hasClickableSpansCache: Boolean? = null
5254
private var selection: TextSelection? = null
5355
private var lastFrameTimeNanos: Long = 0L
5456

@@ -72,8 +74,7 @@ internal class PreparedLayoutTextView(context: Context) : ViewGroup(context), Re
7274
}
7375
}
7476

75-
clickableSpans =
76-
effectiveValue?.layout?.text?.let { filterClickableSpans(it) } ?: emptyList()
77+
hasClickableSpansCache = null
7778

7879
field = effectiveValue
7980
invalidate()
@@ -105,11 +106,11 @@ internal class PreparedLayoutTextView(context: Context) : ViewGroup(context), Re
105106
fun recycleView() {
106107
BackgroundStyleApplicator.reset(this)
107108
overflow = Overflow.VISIBLE
108-
clickableSpans = emptyList()
109109
selection = null
110110
selectionColor = null
111111
lastFrameTimeNanos = 0L
112112
preparedLayout = null
113+
hasClickableSpansCache = null
113114
}
114115

115116
override fun onVisibilityChanged(changedView: View, visibility: Int) {
@@ -277,7 +278,7 @@ internal class PreparedLayoutTextView(context: Context) : ViewGroup(context), Re
277278
}
278279

279280
// Existing ClickableSpan handling
280-
if (clickableSpans.isEmpty()) {
281+
if (!hasClickableSpans()) {
281282
return super.onTouchEvent(event)
282283
}
283284

@@ -301,6 +302,10 @@ internal class PreparedLayoutTextView(context: Context) : ViewGroup(context), Re
301302
return true
302303
}
303304

305+
private fun hasClickableSpans(): Boolean =
306+
hasClickableSpansCache
307+
?: hasClickableSpan(preparedLayout?.layout?.text).also { hasClickableSpansCache = it }
308+
304309
private fun findRootView(): RootView? {
305310
var p: ViewParent? = parent
306311
while (p != null) {
@@ -413,7 +418,7 @@ internal class PreparedLayoutTextView(context: Context) : ViewGroup(context), Re
413418
direction: Int,
414419
previouslyFocusedRect: Rect?,
415420
) {
416-
if (clickableSpans.isNotEmpty() && !gainFocus) {
421+
if (!gainFocus && selection != null) {
417422
clearSelection()
418423
}
419424
super.onFocusChanged(gainFocus, direction, previouslyFocusedRect)
@@ -475,21 +480,10 @@ internal class PreparedLayoutTextView(context: Context) : ViewGroup(context), Re
475480
private companion object {
476481
private val selectionPaint = Paint()
477482

478-
private fun filterClickableSpans(text: CharSequence): List<ClickableSpan> {
479-
if (text !is Spanned) {
480-
return emptyList()
481-
}
482-
483-
val spans = ArrayList<ClickableSpan>()
484-
var i = 0
485-
while (i < text.length) {
486-
val next = text.nextSpanTransition(i, text.length, ClickableSpan::class.java)
487-
spans.addAll(text.getSpans(i, next, ClickableSpan::class.java))
488-
i = next
489-
}
490-
491-
return spans
492-
}
483+
private fun hasClickableSpan(text: CharSequence?): Boolean =
484+
text is Spanned &&
485+
text.isNotEmpty() &&
486+
text.getSpans(0, text.length, ClickableSpan::class.java).isNotEmpty()
493487

494488
/**
495489
* If the layout contains [StatefulSpan]s, returns a new [PreparedLayout] whose spannable has
Lines changed: 141 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,141 @@
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.os.SystemClock
13+
import android.text.Layout
14+
import android.text.Spannable
15+
import android.text.SpannableString
16+
import android.text.TextPaint
17+
import android.text.style.ClickableSpan
18+
import android.view.MotionEvent
19+
import android.view.View
20+
import com.facebook.react.common.annotations.UnstableReactNativeAPI
21+
import com.facebook.react.common.mapbuffer.WritableMapBuffer
22+
import com.facebook.yoga.YogaMeasureMode
23+
import org.assertj.core.api.Assertions.assertThat
24+
import org.junit.Test
25+
import org.junit.runner.RunWith
26+
import org.robolectric.RobolectricTestRunner
27+
import org.robolectric.RuntimeEnvironment
28+
import org.robolectric.annotation.Config
29+
import org.robolectric.annotation.GraphicsMode
30+
31+
/** Tapping a [ClickableSpan] in a [PreparedLayoutTextView] clicks it, for the current text only. */
32+
@OptIn(UnstableReactNativeAPI::class)
33+
@RunWith(RobolectricTestRunner::class)
34+
@SuppressLint("NewApi")
35+
@Config(sdk = [34])
36+
@GraphicsMode(GraphicsMode.Mode.NATIVE)
37+
class PreparedLayoutTextViewClickableSpanTest {
38+
39+
private val view = PreparedLayoutTextView(RuntimeEnvironment.getApplication())
40+
41+
@Test
42+
fun `tapping a clickable span clicks it`() {
43+
val span = CountingClickableSpan()
44+
view.preparedLayout = preparedLayout(textWith(span))
45+
46+
assertThat(tap()).isTrue()
47+
assertThat(span.clicks).isEqualTo(1)
48+
}
49+
50+
@Test
51+
fun `tapping text without clickable spans does not click`() {
52+
val span = CountingClickableSpan()
53+
view.preparedLayout = preparedLayout(textWith(span))
54+
tap()
55+
56+
view.preparedLayout = preparedLayout(SpannableString(TEXT))
57+
58+
assertThat(tap()).isFalse()
59+
assertThat(span.clicks).isEqualTo(1)
60+
}
61+
62+
@Test
63+
fun `tapping a clickable span in new text clicks it`() {
64+
view.preparedLayout = preparedLayout(SpannableString(TEXT))
65+
tap()
66+
67+
val span = CountingClickableSpan()
68+
view.preparedLayout = preparedLayout(textWith(span))
69+
70+
assertThat(tap()).isTrue()
71+
assertThat(span.clicks).isEqualTo(1)
72+
}
73+
74+
@Test
75+
fun `a recycled view does not click spans of its previous text`() {
76+
val span = CountingClickableSpan()
77+
view.preparedLayout = preparedLayout(textWith(span))
78+
tap()
79+
80+
view.recycleView()
81+
82+
assertThat(tap()).isFalse()
83+
assertThat(span.clicks).isEqualTo(1)
84+
}
85+
86+
/** Sends a down and an up at the start of the text; returns whether the up was handled. */
87+
private fun tap(): Boolean {
88+
val time = SystemClock.uptimeMillis()
89+
val down = MotionEvent.obtain(time, time, MotionEvent.ACTION_DOWN, 5f, 5f, 0)
90+
val up = MotionEvent.obtain(time, time, MotionEvent.ACTION_UP, 5f, 5f, 0)
91+
view.onTouchEvent(down)
92+
val handled = view.onTouchEvent(up)
93+
down.recycle()
94+
up.recycle()
95+
return handled
96+
}
97+
98+
private fun textWith(span: ClickableSpan): SpannableString =
99+
SpannableString(TEXT).apply {
100+
setSpan(span, 0, TEXT.length, Spannable.SPAN_INCLUSIVE_INCLUSIVE)
101+
}
102+
103+
private fun preparedLayout(text: SpannableString): PreparedLayout =
104+
PreparedLayout(
105+
TextLayoutManager.createLayout(
106+
text,
107+
/* boring = */ null,
108+
/* width = */ 400f,
109+
YogaMeasureMode.EXACTLY,
110+
/* includeFontPadding = */ false,
111+
/* textBreakStrategy = */ Layout.BREAK_STRATEGY_HIGH_QUALITY,
112+
/* hyphenationFrequency = */ Layout.HYPHENATION_FREQUENCY_NONE,
113+
/* lineBreakStyle = */ LineBreakConfig.LINE_BREAK_STYLE_NONE,
114+
/* lineBreakWordStyle = */ LineBreakConfig.LINE_BREAK_WORD_STYLE_NONE,
115+
Layout.Alignment.ALIGN_NORMAL,
116+
/* justificationMode = */ 0,
117+
/* ellipsizeMode = */ null,
118+
/* maxNumberOfLines = */ 0,
119+
TextPaint(TextPaint.ANTI_ALIAS_FLAG).apply { textSize = 26f },
120+
),
121+
/* maximumNumberOfLines = */ 0,
122+
/* verticalOffset = */ 0f,
123+
/* reactTags = */ IntArray(0),
124+
/* textBreakStrategy = */ Layout.BREAK_STRATEGY_HIGH_QUALITY,
125+
/* justificationMode = */ 0,
126+
baseTextAttributes = TextAttributeProps.fromMapBuffer(WritableMapBuffer()),
127+
/* sourceText = */ text,
128+
)
129+
130+
private class CountingClickableSpan : ClickableSpan() {
131+
var clicks = 0
132+
133+
override fun onClick(widget: View) {
134+
clicks++
135+
}
136+
}
137+
138+
private companion object {
139+
const val TEXT = "Tap this text"
140+
}
141+
}

0 commit comments

Comments
 (0)