From f402ed17fa6d75aea24e2ad99a8b8d8ad20840e3 Mon Sep 17 00:00:00 2001 From: Kacper Kafara Date: Wed, 4 Dec 2024 15:24:35 -0800 Subject: [PATCH] Fix handling removal of transitioning views (#47634) Summary: Related PR in `react-native-screens`: * https://github.com/software-mansion/react-native-screens/pull/2495 Additional context: * [my detailed explanation of **one of the issues**](https://github.com/software-mansion/react-native-screens/pull/2495#issuecomment-2478915818) * [Android Developer: ViewGroup.startViewTransition docs](https://developer.android.com/reference/android/view/ViewGroup#startViewTransition(android.view.View)) ### Background On Android view groups can be marked as "transitioning" with a `ViewGroup.startViewTransition` call. This effectively ensures, that in case a view group is marked with this call and its children are removed, they will be still drawn until `endViewTransition` is not called. This mechanism is implemented in Android by [keeping track of "transitioning" children in auxiliary `mTransitioningViews` array](https://android.googlesource.com/platform/frameworks/base/+/master/core/java/android/view/ViewGroup.java#7178). Then when such "transitioning" child is removed, [it is removed from children array](https://android.googlesource.com/platform/frameworks/base/+/master/core/java/android/view/ViewGroup.java#5595) but it's [parent-child relationship is not cleared](https://android.googlesource.com/platform/frameworks/base/+/master/core/java/android/view/ViewGroup.java#5397) and it is still retained in the auxiliary array. Having that established we can proceed with problem description. ### Problem https://github.com/user-attachments/assets/d0356bf5-2f17-4b06-ba53-bfca659a1071
Full code ```javascript import { NavigationContainer } from 'react-navigation/native'; import React from 'react'; import { createNativeStackNavigator } from 'react-navigation/native-stack'; import { enableScreens } from 'react-native-screens'; import { StyleSheet, Text, View, FlatList, Button, ViewProps, Image, FlatListProps, findNodeHandle, } from 'react-native'; enableScreens(true); function Item({ children, ...props }: ViewProps) { return ( {children} ); } function Home({ navigation }: any) { return (
Explanation (copied from [here](https://github.com/software-mansion/react-native-screens/pull/2495#issuecomment-2478915818)): I've debugged this for a while now & I have good understanding of what's going on. This bug is caused by our usage of `startViewTransition` and its implications. We use it well, however React does not account for case that some view might be in transition. Error mechanism is as follows: 1. Let's have initially simple stack with two screens: "A, B". This is component rendered under "B": ```javascript // <--- IntermediateView (IV) // <--- ChildView (ChV) ``` 2. We press the back button. 3. We're on Fabric, therefore subtree of B gets destroyed before B itself is unmounted -> in our commit hook we detect that the screen B will be unmounted & we mark every node under B as transitioning by calling `startViewTransition`. 4. React Mounting stage starts, view hierarchy is disassembled in bottom-up fashion (leafs first). 5. ReactViewGroupManager receives MountItem to detach ChV from IV. 6. A call to [`IV.removeView(ChV)` is made](https://github.com/facebook/react-native/blob/9c11d7ca68c5c62ab7bab9919161d8417e96b28b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/view/ReactClippingViewManager.kt#L58-L73), which effectively removes ChV from `IV.children`, ***HOWEVER*** it does not clear `ChV.parent`, meaning that after the call, `ChV.parent == IV`. This happens, due to view being marked as in-transition by our call to `startViewTransition`. If the view is not marked as in-transition this parent-child relationship is removed. 7. IV has `removeClippedSubviews` enabled, therefore a [call to `IV.removeViewWithSubviewsClippingEnabled(ChV)` is made](https://github.com/facebook/react-native/blob/9c11d7ca68c5c62ab7bab9919161d8417e96b28b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/view/ReactClippingViewManager.kt#L68). [This function](https://github.com/facebook/react-native/blob/9c11d7ca68c5c62ab7bab9919161d8417e96b28b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/view/ReactViewGroup.java#L726-L744) does effectively two things: 1. if the ChV has parent (interpretation: it has not yet been detached from parent), we compute it's index in `IV.children` (Android.ViewGroup's state) and remove it from the array, 2. remove the ChV from `mAllChildren` array (this is state maintained by ReactViewGroup for purposes of implementing the "subview clipping" mechanism". The crash happens in 7.1, because ChV has been removed from `IV.children` in step 6, but the parent-child relationship has not been broken up there. Under usual circumstances (this is my hypothesis now, yet unconfirmed) 7.1 does not execute, because `ChV.parent` is nulled in step no. 6. ### Rationale for `startViewTransition` usage Transitions. On Fabric, when some subtree is unmounted, views in the subtree are unmounted in bottom-up order. This leads to uncomfortable situation, where our components (react-native-screens), who want to drive & manage transitions are notified that their children will be removed after the subtrees mounted in screen subviews are already disassembled. **If we start animation in this very moment we will have staggering effect of white flash** [(issue)](https://github.com/software-mansion/react-native-screens/issues/1685) (we animate just the screen with white background without it's children). This was not a problem on Paper, because the order of subtree disassembling was opposite - top-down. While we've managed to workaround this issue on Fabric using `MountingTransactionObserving` protocol on iOS and a commit hook on Android (we can inspect mutations in incoming transaction before it starts being applied) we still need to prevent view hierarchy from being disassembled in the middle of transition (on Paper this has also been less of an issue) - and this is where `startViewTransition` comes in. It allows us to draw views throughout transition after React Native removes them from HostTree model. On iOS we exchange subtree for its snapshot for transition time, however this approach isn't feasible on Android, because [snapshots do not capture shadows](https://stackoverflow.com/questions/42212600/android-screenshot-of-view-with-shadow). ### Possible solutions [Android does not expose a method to verify whether a view is in transition](https://android.googlesource.com/platform/frameworks/base/+/master/core/java/android/view/ViewGroup.java#7162) (it has `package` visibility), therefore we need to retrieve this information with some workaround. I see two posibilities: * first approach would be to override `startViewTransition` & `endViewTransition` in ReactViewGroup and keep the state on whether the view is transitioning there, * second possible approach would be as follows: we can check for "transitioning" view by checking whether a view has parent but is not it's parent child (this **should** be reliable), Having information on whether the view is in transition or not, we can prevent multiple removals of the same view in every call site (currently only in `removeViewAt` if `parent.removeClippingSubviews == true`). Another option would be to do just as this PR does: having in mind this "transitioning" state we can pass a flag to `removeViewWithSubviewClippingEnabled` and prevent duplicated removal from parent if we already know that this has been requested. I can also add override of this method: ```java /*package*/ void removeViewWithSubviewClippingEnabled(View view) { this.removeViewWithSubviewClippingEnabled(view, false); } ``` to make this parameter optional. ## Changelog: [ANDROID] [FIXED] - Handle removal of in-transition views. Pull Request resolved: https://github.com/facebook/react-native/pull/47634 Test Plan: WIP WIP Reviewed By: javache Differential Revision: D66539065 Pulled By: tdn120 fbshipit-source-id: cf1add67000ebd1b5dfdb2048461a55deac10b16 --- .../ReactAndroid/api/ReactAndroid.api | 1 + .../views/view/ReactClippingViewManager.kt | 3 -- .../react/views/view/ReactViewGroup.java | 38 +++++++++++++++++-- 3 files changed, 36 insertions(+), 6 deletions(-) diff --git a/packages/react-native/ReactAndroid/api/ReactAndroid.api b/packages/react-native/ReactAndroid/api/ReactAndroid.api index a87602943a0b11..ef61834f169bac 100644 --- a/packages/react-native/ReactAndroid/api/ReactAndroid.api +++ b/packages/react-native/ReactAndroid/api/ReactAndroid.api @@ -7772,6 +7772,7 @@ public class com/facebook/react/views/view/ReactViewGroup : android/view/ViewGro protected fun dispatchSetPressed (Z)V public fun draw (Landroid/graphics/Canvas;)V protected fun drawChild (Landroid/graphics/Canvas;Landroid/view/View;J)Z + public fun endViewTransition (Landroid/view/View;)V protected fun getChildDrawingOrder (II)I public fun getClippingRect (Landroid/graphics/Rect;)V public fun getHitSlopRect ()Landroid/graphics/Rect; diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/view/ReactClippingViewManager.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/view/ReactClippingViewManager.kt index da19e945b52a9b..2f2453e97a1d0d 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/view/ReactClippingViewManager.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/view/ReactClippingViewManager.kt @@ -62,9 +62,6 @@ public abstract class ReactClippingViewManager : ViewGroupMa if (removeClippedSubviews) { val child = getChildAt(parent, index) if (child != null) { - if (child.parent != null) { - parent.removeView(child) - } parent.removeViewWithSubviewClippingEnabled(child) } } else { diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/view/ReactViewGroup.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/view/ReactViewGroup.java index ce6eb2c838b71e..a245f7ffae273b 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/view/ReactViewGroup.java +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/view/ReactViewGroup.java @@ -138,6 +138,7 @@ public void shutdown() { private @Nullable ViewGroupDrawingOrderHelper mDrawingOrderHelper; private float mBackfaceOpacity; private String mBackfaceVisibility; + private @Nullable Set mChildrenRemovedWhileTransitioning; /** * Creates a new `ReactViewGroup` instance. @@ -172,6 +173,7 @@ private void initView() { mDrawingOrderHelper = null; mBackfaceOpacity = 1.f; mBackfaceVisibility = "visible"; + mChildrenRemovedWhileTransitioning = null; } /* package */ void recycleView() { @@ -354,6 +356,7 @@ public void setRemoveClippedSubviews(boolean removeClippedSubviews) { return; } mRemoveClippedSubviews = removeClippedSubviews; + mChildrenRemovedWhileTransitioning = null; if (removeClippedSubviews) { mClippingRect = new Rect(); ReactClippingViewGroupHelper.calculateClippingRect(this, mClippingRect); @@ -408,6 +411,26 @@ public void updateClippingRect() { updateClippingToRect(mClippingRect); } + @Override + public void endViewTransition(View view) { + super.endViewTransition(view); + if (mChildrenRemovedWhileTransitioning != null) { + mChildrenRemovedWhileTransitioning.remove(view.getId()); + } + } + + private void trackChildViewTransition(int childId) { + if (mChildrenRemovedWhileTransitioning == null) { + mChildrenRemovedWhileTransitioning = new HashSet<>(); + } + mChildrenRemovedWhileTransitioning.add(childId); + } + + private boolean isChildRemovedWhileTransitioning(View child) { + return mChildrenRemovedWhileTransitioning != null + && mChildrenRemovedWhileTransitioning.contains(child.getId()); + } + private void updateClippingToRect(Rect clippingRect) { Assertions.assertNotNull(mAllChildren); mInSubviewClippingLoop = true; @@ -573,6 +596,12 @@ public void onViewRemoved(View child) { } else { setChildrenDrawingOrderEnabled(false); } + + // The parent might not be null in case the child is transitioning. + if (child.getParent() != null) { + trackChildViewTransition(child.getId()); + } + super.onViewRemoved(child); } @@ -745,6 +774,7 @@ private boolean isViewClipped(View view, @Nullable Integer index) { return (boolean) tag; } ViewParent parent = view.getParent(); + boolean transitioning = isChildRemovedWhileTransitioning(view); if (index != null) { ReactSoftExceptionLogger.logSoftException( "ReactViewGroup.isViewClipped", @@ -754,10 +784,12 @@ private boolean isViewClipped(View view, @Nullable Integer index) { + " parentNull=" + (parent == null) + " parentThis=" - + (parent == this))); + + (parent == this) + + " transitioning=" + + transitioning)); } - // fallback - parent *should* be null if the view was removed - if (parent == null) { + // fallback - should be transitioning or have no parent if the view was removed + if (parent == null || transitioning) { return true; } else { Assertions.assertCondition(parent == this);