Fix addViewAt crash for views held by startViewTransition on Android

<!-- Thanks for submitting a pull request! We appreciate you spending the time to work on these changes. Please provide enough information so that others can review your pull request. The three fields below are mandatory. -->

## Summary:

<!-- Explain the **motivation** for making this change. What existing problem does the pull request solve? -->

On Android, `SurfaceMountingManager.addViewAt` fails when it inserts a view that a parent still holds with `ViewGroup.startViewTransition`.

A held child can leave its old parent's child list while `child.parent` still points to that old parent:

```text
oldParent.indexOfChild(view) == -1
view.parent == oldParent
```

The existing recovery in `addViewAt` calls `removeView` on the old parent. That does nothing for a view that is no longer in the child list, so `addView` throws `addViewAt: failed to insert view ... into parent`. The recovery also adds the tag to `erroneouslyReaddedReactTags`, so a later Remove of that tag returns early and the view is never removed.

React Native Screens holds the content of a removed screen this way during its exit animation ([`Screen.startRemovalTransition`](https://github.com/software-mansion/react-native-screens/blob/4.27.0/android/src/main/java/com/swmansion/rnscreens/Screen.kt), [`NativeProxy.notifyScreenRemoved`](https://github.com/software-mansion/react-native-screens/blob/4.27.0/android/src/fabric/java/com/swmansion/rnscreens/NativeProxy.kt)).
Reanimated shared element transitions will soon move the source view out of such a screen into the surface root ([react-native-reanimated#11054](https://github.com/software-mansion/react-native-reanimated/pull/11054)), and the app crashes when going back.
Analysis: [comment on #11054](https://github.com/software-mansion/react-native-reanimated/pull/11054#issuecomment-6501799104).
Reanimated is getting a workaround that releases the holds before the mount batch ([react-native-reanimated#11101](https://github.com/software-mansion/react-native-reanimated/pull/11101)), but `addViewAt` is the better place for the fix.

### The fix

Before the existing recovery, if the old parent no longer lists the view, call [`endViewTransition`](https://developer.android.com/reference/android/view/ViewGroup#endViewTransition(android.view.View)) on it, then read `view.parent` again. If the parent is cleared, the view is inserted normally and the tag is not marked as re-added. If the parent is still set, the existing recovery and its diagnostics run as before.

- Holds of removed views that are not inserted again stay in place, so normal exit animations do not change.
- A view held more than once, for example by nested screens, is released by one call, because `endViewTransition` clears the parent when it removes the view from the disappearing children.
- Nested carriers each go through the same check on their own insert.
- `ReactViewGroup.endViewTransition` also clears its own `childrenRemovedWhileTransitioning` entry, so RN's clipping state stays in sync.

## Changelog:

<!-- Help reviewers and the release process by writing your own changelog entry.

Pick one each for the category and type tags:

[ANDROID|GENERAL|IOS|INTERNAL] [BREAKING|ADDED|CHANGED|DEPRECATED|REMOVED|FIXED|SECURITY] - Message

For more details, see:
https://reactnative.dev/contributing/changelogs-in-pull-requests
-->

[ANDROID] [FIXED] - Fix `addViewAt` crash when a view that a parent still holds with `startViewTransition` is inserted into another parent

## Test Plan:

<!-- Demonstrate the code is solid. Example: The exact commands you ran and their output, screenshots / videos if the pull request changes the user interface. -->

New Robolectric tests in `SurfaceMountingManagerViewTransitionTest`, with the real `SurfaceMountingManager` and real Android `ViewGroup`s:

```sh
./gradlew :packages:react-native:ReactAndroid:testDebugUnitTest \
  --tests 'com.facebook.react.fabric.SurfaceMountingManagerViewTransitionTest'
```

| Test | Without fix | With fix |
| --- | --- | --- |
| held child moves to root, then final removal | fails: `addViewAt: failed to insert view [12] into parent [1] at index 1` | passes |
| nested held children (each parent holds twice, carrier in carrier) move, then final removal | fails (same error) | passes |
| held child moves with the root attached to a window | fails (same error) | passes |
| held child is put back into its old parent | fails: `... into parent [10] at index 0` | passes |
| control: held exit with no reinsert keeps its hold | passes | passes |
| control: unheld move | passes | passes |
| control: existing recovery for a child that another parent still lists | passes | passes |

Other checks:

```sh
./gradlew :packages:react-native:ReactAndroid:testDebugUnitTest --tests 'com.facebook.react.fabric.*' -PenableWarningsAsErrors=true  # 89 tests, 0 failures
./gradlew :packages:react-native:ReactAndroid:lintDebug -PenableWarningsAsErrors=true  # no issues in changed files
yarn format-check-kotlin  # pass
```

Device test: Reanimated `apps/fabric-example` (branch of #11054, without #11101), Android emulator, Debug, `--active-arch-only`, React Native built from source. The example app does not build against `main` (it needs RN 0.86 to 0.88), so this used `v0.88.0` with only this `SurfaceMountingManager.kt` change applied.

- Without the fix: Shared Element Transitions → Fade Content → Sun, wait for the push to end, tap the content to go back. The app crashes with `addViewAt: failed to insert view [666] into parent [1] at index 3. The specified child already has a parent.`
- With the fix: the same path (3 times), the hardware Back button (4 times), a quick pop during the push, nested shared tags, and nested stack navigation. No crash, no `addViewAt` or "already has a parent" lines in logcat, and no shared view is left on the root after the pop.

### Recordings

**Before:** 

https://github.com/user-attachments/assets/40cd095f-909e-47b4-b741-16cdc9751bba

**After:**

https://github.com/user-attachments/assets/db6d35b5-c9e7-40ec-8632-2b96f79188f6

Differential Revision: D129333127

Pull Request resolved: https://github.com/react/react-native/pull/59776
This commit is contained in:
Oskar Pawica authored and GitHub committed 2026-11-04 13:31:52 +00:00
1 parent f6c9a855ae
commit 45152f1f85
2 files changed
+236 -1

No files matched your search

@@ -335,7 +335,11 @@ internal constructor(
logViewHierarchy(parentView, false)
}
val currParentView = view.parent
var currParentView = view.parent
if (currParentView is ViewGroup && currParentView.indexOfChild(view) == -1) {
currParentView.endViewTransition(view)
currParentView = view.parent
}
if (currParentView != null) {
val actualParentId = if (currParentView is ViewGroup) currParentView.id else View.NO_ID
ReactSoftExceptionLogger.logSoftException(
@@ -0,0 +1,231 @@
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
@file:Suppress("DEPRECATION")
package com.facebook.react.fabric
import android.app.Activity
import android.view.View
import android.view.ViewGroup
import com.facebook.react.ReactRootView
import com.facebook.react.bridge.JavaOnlyMap
import com.facebook.react.bridge.ReactTestHelper
import com.facebook.react.fabric.mounting.MountingManager
import com.facebook.react.fabric.mounting.MountingManager.MountItemExecutor
import com.facebook.react.fabric.mounting.SurfaceMountingManager
import com.facebook.react.internal.featureflags.ReactNativeFeatureFlagsForTests
import com.facebook.react.uimanager.ThemedReactContext
import com.facebook.react.uimanager.ViewManager
import com.facebook.react.uimanager.ViewManagerRegistry
import com.facebook.react.views.view.ReactViewManager
import com.facebook.testutils.shadows.ShadowSoLoader
import org.assertj.core.api.Assertions.assertThat
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.Robolectric
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
/**
* Tests for [SurfaceMountingManager.addViewAt] with views that a parent still holds with
* [ViewGroup.startViewTransition] after their removal.
*/
@RunWith(RobolectricTestRunner::class)
@Config(shadows = [ShadowSoLoader::class])
class SurfaceMountingManagerViewTransitionTest {
private lateinit var mountingManager: MountingManager
private lateinit var themedReactContext: ThemedReactContext
private val surfaceId = 1
@Before
fun setUp() {
ReactNativeFeatureFlagsForTests.setUp()
val reactContext = ReactTestHelper.createTestReactApplicationContext()
themedReactContext = ThemedReactContext(reactContext, reactContext, null, -1)
mountingManager =
MountingManager(
ViewManagerRegistry(listOf<ViewManager<*, *>>(ReactViewManager())),
MountItemExecutor {},
)
}
@Test
fun addViewAt_movesHeldChildAndAllowsItsFinalRemoval() {
val smm = startSurface()
smm.createViews(SCREEN, CARRIER)
smm.addViewAt(surfaceId, SCREEN, 0)
smm.addViewAt(SCREEN, CARRIER, 0)
val screen = smm.viewGroup(SCREEN)
val carrier = smm.getView(CARRIER)
screen.startViewTransition(carrier)
smm.removeViewAt(CARRIER, SCREEN, 0)
assertThat(carrier.parent).isSameAs(screen)
smm.addViewAt(surfaceId, CARRIER, 1)
assertThat(carrier.parent).isSameAs(smm.viewGroup(surfaceId))
smm.removeViewAt(CARRIER, surfaceId, 1)
assertThat(carrier.parent).isNull()
assertThat(smm.viewGroup(surfaceId).indexOfChild(carrier)).isEqualTo(-1)
}
@Test
fun addViewAt_movesNestedHeldChildrenAndAllowsTheirFinalRemoval() {
val smm = startSurface()
smm.createViews(SCREEN, CONTENT, CARRIER, INNER_CARRIER)
smm.addViewAt(surfaceId, SCREEN, 0)
smm.addViewAt(SCREEN, CONTENT, 0)
smm.addViewAt(CONTENT, CARRIER, 0)
smm.addViewAt(CARRIER, INNER_CARRIER, 0)
val root = smm.viewGroup(surfaceId)
val carrier = smm.getView(CARRIER)
val innerCarrier = smm.getView(INNER_CARRIER)
repeat(2) {
smm.viewGroup(SCREEN).startViewTransition(smm.getView(CONTENT))
smm.viewGroup(CONTENT).startViewTransition(carrier)
smm.viewGroup(CARRIER).startViewTransition(innerCarrier)
}
smm.removeViewAt(INNER_CARRIER, CARRIER, 0)
smm.removeViewAt(CARRIER, CONTENT, 0)
assertThat(carrier.parent).isSameAs(smm.viewGroup(CONTENT))
assertThat(innerCarrier.parent).isSameAs(carrier)
smm.addViewAt(surfaceId, CARRIER, 1)
smm.addViewAt(surfaceId, INNER_CARRIER, 2)
assertThat(carrier.parent).isSameAs(root)
assertThat(innerCarrier.parent).isSameAs(root)
smm.removeViewAt(INNER_CARRIER, surfaceId, 2)
smm.removeViewAt(CARRIER, surfaceId, 1)
assertThat(innerCarrier.parent).isNull()
assertThat(carrier.parent).isNull()
assertThat(root.childCount).isEqualTo(1)
}
@Test
fun addViewAt_movesHeldChildOfRootAttachedToWindow() {
val smm = startSurface()
attachToWindow(smm.getView(surfaceId))
smm.createViews(SCREEN, CARRIER)
smm.addViewAt(surfaceId, SCREEN, 0)
smm.addViewAt(SCREEN, CARRIER, 0)
val carrier = smm.getView(CARRIER)
smm.viewGroup(SCREEN).startViewTransition(carrier)
smm.removeViewAt(CARRIER, SCREEN, 0)
assertThat(carrier.isAttachedToWindow).isTrue()
smm.addViewAt(surfaceId, CARRIER, 1)
assertThat(carrier.parent).isSameAs(smm.viewGroup(surfaceId))
assertThat(carrier.isAttachedToWindow).isTrue()
smm.removeViewAt(CARRIER, surfaceId, 1)
assertThat(carrier.parent).isNull()
assertThat(carrier.isAttachedToWindow).isFalse()
}
@Test
fun addViewAt_reinsertsHeldChildIntoItsOldParent() {
val smm = startSurface()
smm.createViews(SCREEN, CONTENT, CARRIER)
smm.addViewAt(surfaceId, SCREEN, 0)
smm.addViewAt(SCREEN, CONTENT, 0)
smm.addViewAt(SCREEN, CARRIER, 1)
val screen = smm.viewGroup(SCREEN)
val carrier = smm.getView(CARRIER)
screen.startViewTransition(carrier)
smm.removeViewAt(CARRIER, SCREEN, 1)
smm.addViewAt(SCREEN, CARRIER, 0)
assertThat(screen.indexOfChild(carrier)).isEqualTo(0)
smm.removeViewAt(CARRIER, SCREEN, 0)
assertThat(carrier.parent).isNull()
}
@Test
fun addViewAt_keepsHoldOfRemovedChildThatIsNotReinserted() {
val smm = startSurface()
smm.createViews(SCREEN, CONTENT, NEXT_SCREEN)
smm.addViewAt(surfaceId, SCREEN, 0)
smm.addViewAt(SCREEN, CONTENT, 0)
val screen = smm.viewGroup(SCREEN)
val content = smm.getView(CONTENT)
screen.startViewTransition(content)
smm.removeViewAt(CONTENT, SCREEN, 0)
smm.addViewAt(surfaceId, NEXT_SCREEN, 1)
assertThat(content.parent).isSameAs(screen)
assertThat(screen.indexOfChild(content)).isEqualTo(-1)
}
@Test
fun addViewAt_movesChildThatIsNotHeld() {
val smm = startSurface()
smm.createViews(SCREEN, NEXT_SCREEN, CARRIER)
smm.addViewAt(surfaceId, SCREEN, 0)
smm.addViewAt(surfaceId, NEXT_SCREEN, 1)
smm.addViewAt(SCREEN, CARRIER, 0)
val carrier = smm.getView(CARRIER)
smm.removeViewAt(CARRIER, SCREEN, 0)
smm.addViewAt(NEXT_SCREEN, CARRIER, 0)
assertThat(carrier.parent).isSameAs(smm.viewGroup(NEXT_SCREEN))
smm.removeViewAt(CARRIER, NEXT_SCREEN, 0)
assertThat(carrier.parent).isNull()
}
@Test
fun addViewAt_keepsRecoveryForChildThatAnotherParentStillLists() {
val smm = startSurface()
smm.createViews(SCREEN, NEXT_SCREEN, CARRIER)
smm.addViewAt(surfaceId, SCREEN, 0)
smm.addViewAt(surfaceId, NEXT_SCREEN, 1)
smm.addViewAt(SCREEN, CARRIER, 0)
val nextScreen = smm.viewGroup(NEXT_SCREEN)
val carrier = smm.getView(CARRIER)
smm.addViewAt(NEXT_SCREEN, CARRIER, 0)
assertThat(carrier.parent).isSameAs(nextScreen)
assertThat(smm.viewGroup(SCREEN).indexOfChild(carrier)).isEqualTo(-1)
smm.removeViewAt(CARRIER, NEXT_SCREEN, 0)
assertThat(carrier.parent).isSameAs(nextScreen)
}
private fun startSurface(): SurfaceMountingManager {
val rootView = ReactRootView(themedReactContext)
mountingManager.startSurface(surfaceId, themedReactContext, rootView)
return mountingManager.getSurfaceManagerEnforced(surfaceId, "test")
}
private fun attachToWindow(view: View) {
Robolectric.buildActivity(Activity::class.java).setup().get().setContentView(view)
}
private fun SurfaceMountingManager.createViews(vararg tags: Int) {
for (tag in tags) {
createView("RCTView", tag, JavaOnlyMap.of(), null, null, true)
}
}
private fun SurfaceMountingManager.viewGroup(tag: Int): ViewGroup = getView(tag) as ViewGroup
private companion object {
const val SCREEN = 10
const val CONTENT = 11
const val CARRIER = 12
const val INNER_CARRIER = 13
const val NEXT_SCREEN = 14
}
}