Skip to content

Commit c3c3b7b

Browse files
authored
Report Android safe-area insets after a last-pixel change settles
## Summary: `SafeAreaInsetsObserver` reports a view's safe-area insets only when an edge moves more than one physical pixel from the last report, to match iOS's precision while the view moves. A change within that threshold is dropped for good. The last frame of a transition often moves a view by its last pixel, so a screen that slides in from the side can keep the one-pixel inset it had on the frame before it stopped. Which frames the observer sees varies, so the same screen can end with different insets each time it opens. This change holds a change within the threshold and requests another frame (`postInvalidateOnAnimation`): - If the insets are the same on the next frame, they have settled and are reported. - If they moved again, they are held again. A view that moves a pixel or less per frame sends nothing until it stops or moves past the threshold. - Insets within 0.01 px of the last report count as unchanged, so a settled view sends nothing more. The threshold while the view moves is unchanged. ## Changelog: [ANDROID] [FIXED] - Report a view's safe-area insets when a change of one pixel or less settles ## Test Plan: ```sh ./gradlew :packages:react-native:ReactAndroid:testDebugUnitTest --tests com.facebook.react.uimanager.SafeAreaInsetsObserverTest -Preact.internal.useHermesStable=true --console=plain ``` The new `lastPixelOfASlideIn_isReportedOnceTheViewHoldsStill` moves a view in by 3, 1 and 0 px of `translationX`, and expects the last pixel to be reported as `right: 0` on the frame after the view stops, and no report on the frame after that. It also expects one `postInvalidateOnAnimation` call, made on the frame the view stops: the test calls `onPreDraw` itself, and on a device nothing else would draw that next frame. The test fails on `main`, and fails with the `postInvalidateOnAnimation` call removed (0 frame requests instead of 1). The observer keeps the held frame's insets as well as the last reported ones. Without them it cannot tell a view that has stopped from one still moving within the threshold, and `subpixelChanges_emitOnlyBeyondOnePhysicalPixelWithoutRoundingPayload` fails. ktfmt and `git diff --check` are clean. Not run: a device or emulator. Differential Revision: D135308620 Pull Request resolved: #60373
1 parent 91668b3 commit c3c3b7b

2 files changed

Lines changed: 75 additions & 5 deletions

File tree

‎packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/internal/SafeAreaInsetsObserver.kt‎

Lines changed: 24 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -30,8 +30,10 @@ internal class SafeAreaInsetsObserver private constructor(private val view: View
3030
private val geometry = Geometry()
3131
private val insets = FloatArray(4)
3232
private val lastInsets = FloatArray(4)
33+
private val pendingInsets = FloatArray(4)
3334

3435
private var hasLastInsets = false
36+
private var hasPendingInsetsToApply = false
3537
private var isListening = false
3638

3739
private fun start() {
@@ -89,18 +91,30 @@ internal class SafeAreaInsetsObserver private constructor(private val view: View
8991
hasLastInsets = false
9092
return
9193
}
92-
if (
93-
hasLastInsets &&
94-
insets.indices.all { abs(insets[it] - lastInsets[it]) <= INSET_CHANGE_THRESHOLD_PX }
95-
) {
96-
return
94+
if (hasLastInsets && within(insets, lastInsets, INSET_CHANGE_THRESHOLD_PX)) {
95+
// A change within the threshold is not reported while the view moves, but the last frame of
96+
// a transition often moves the view by its last pixel. Hold the change and draw another
97+
// frame; insets that are the same on that frame have settled and are reported. The
98+
// comparison is with the held frame, not with `lastInsets`: the last report cannot tell a
99+
// view that has stopped from one still moving within the threshold.
100+
if (within(insets, lastInsets, INSET_ROUND_OFF_PX)) {
101+
hasPendingInsetsToApply = false
102+
return
103+
}
104+
if (!hasPendingInsetsToApply || !within(insets, pendingInsets, INSET_ROUND_OFF_PX)) {
105+
insets.copyInto(pendingInsets)
106+
hasPendingInsetsToApply = true
107+
view.postInvalidateOnAnimation()
108+
return
109+
}
97110
}
98111
val eventDispatcher =
99112
UIManagerHelper.getEventDispatcher(UIManagerHelper.getReactContext(view)) ?: return
100113
// Recorded only once the event is actually dispatched, so a failed lookup
101114
// above does not permanently swallow this inset value.
102115
insets.copyInto(lastInsets)
103116
hasLastInsets = true
117+
hasPendingInsetsToApply = false
104118
eventDispatcher.dispatchEvent(
105119
SafeAreaInsetsChangeEvent(
106120
surfaceId = UIManagerHelper.getSurfaceId(view),
@@ -113,6 +127,9 @@ internal class SafeAreaInsetsObserver private constructor(private val view: View
113127
)
114128
}
115129

130+
private fun within(a: FloatArray, b: FloatArray, tolerance: Float): Boolean =
131+
a.indices.all { abs(a[it] - b[it]) <= tolerance }
132+
116133
private class Geometry {
117134
val visibleRect = Rect()
118135
val toRoot = Matrix()
@@ -127,6 +144,8 @@ internal class SafeAreaInsetsObserver private constructor(private val view: View
127144
private const val LEFT = 3
128145
// Match iOS notification precision without rounding the emitted measurement.
129146
private const val INSET_CHANGE_THRESHOLD_PX = 1f
147+
// A transformed edge's float round-off, far below any change worth reporting.
148+
private const val INSET_ROUND_OFF_PX = 0.01f
130149
// Bound accumulated transform round-off to one thousandth of a physical pixel.
131150
private const val MAX_AXIS_ALIGNMENT_ERROR_PX = 0.001f
132151

‎packages/react-native/ReactAndroid/src/test/java/com/facebook/react/uimanager/SafeAreaInsetsObserverTest.kt‎

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -531,6 +531,57 @@ class SafeAreaInsetsObserverTest {
531531
assertThat(insets.getDouble("bottom")).isEqualTo(50.625)
532532
}
533533

534+
@Test
535+
@Suppress("DEPRECATION")
536+
@SuppressLint("DeprecatedMethod")
537+
fun lastPixelOfASlideIn_isReportedOnceTheViewHoldsStill() {
538+
// A screen sliding in from the right: its last frame moves it one pixel, which is within the
539+
// threshold of the frame before.
540+
DisplayMetricsHolder.setScreenDisplayMetrics(DisplayMetrics().apply { density = 2f })
541+
var frameRequests = 0
542+
val view =
543+
object : View(root.context) {
544+
override fun postInvalidateOnAnimation() {
545+
frameRequests++
546+
}
547+
}
548+
root.addView(view)
549+
view.layout(40, 100, 460, 900)
550+
val observer = observe(view)
551+
view.translationX = 3f
552+
observer.onPreDraw()
553+
view.translationX = 1f
554+
observer.onPreDraw()
555+
assertThat(frameRequests).isEqualTo(0)
556+
view.translationX = 0f
557+
observer.onPreDraw()
558+
assertThat(events).hasSize(2)
559+
// Nothing else draws once the view has stopped, so the observer has to request the frame on
560+
// which it reports the held change.
561+
assertThat(frameRequests).isEqualTo(1)
562+
563+
observer.onPreDraw()
564+
assertThat(events).hasSize(3)
565+
val emitter = mock<RCTModernEventEmitter>()
566+
val payload = argumentCaptor<WritableMap>()
567+
events.last().dispatchModern(emitter)
568+
verify(emitter)
569+
.receiveEvent(
570+
eq(1),
571+
eq(2),
572+
eq("topSafeAreaInsetsChange"),
573+
any(),
574+
any(),
575+
payload.capture(),
576+
any(),
577+
)
578+
assertThat(checkNotNull(payload.firstValue.getMap("insets")).getDouble("right")).isEqualTo(0.0)
579+
580+
observer.onPreDraw()
581+
assertThat(events).hasSize(3)
582+
assertThat(frameRequests).isEqualTo(1)
583+
}
584+
534585
@Test
535586
fun supportedUnsupportedSupported_reEmitsAfterRecovery() {
536587
val view = addView(root, 0, 0, 500, 1000)

0 commit comments

Comments
 (0)