From 5d10a7b60e5615460ed02afcb508693e30388c6d Mon Sep 17 00:00:00 2001 From: Pieter De Baets Date: Fri, 23 Jan 2026 06:46:18 -0800 Subject: [PATCH] xplat/js/react-native-github/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/fabric/mounting/SurfaceMountingManager.java (#55174) Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/55174 Reviewed By: cortinico Differential Revision: D90111698 --- .../ReactAndroid/api/ReactAndroid.api | 69 +- .../react/fabric/FabricUIManager.java | 4 +- .../react/fabric/mounting/MountingManager.kt | 4 +- .../mounting/SurfaceMountingManager.java | 1411 ----------------- .../fabric/mounting/SurfaceMountingManager.kt | 1257 +++++++++++++++ .../mountitems/IntBufferBatchMountItem.kt | 4 +- .../mounting/mountitems/MountItemFactory.kt | 2 +- .../mountitems/PreAllocateViewMountItem.kt | 2 +- 8 files changed, 1299 insertions(+), 1454 deletions(-) delete mode 100644 packages/react-native/ReactAndroid/src/main/java/com/facebook/react/fabric/mounting/SurfaceMountingManager.java create mode 100644 packages/react-native/ReactAndroid/src/main/java/com/facebook/react/fabric/mounting/SurfaceMountingManager.kt diff --git a/packages/react-native/ReactAndroid/api/ReactAndroid.api b/packages/react-native/ReactAndroid/api/ReactAndroid.api index 5a53ab66b99760..42e5d67c375f1e 100644 --- a/packages/react-native/ReactAndroid/api/ReactAndroid.api +++ b/packages/react-native/ReactAndroid/api/ReactAndroid.api @@ -2311,41 +2311,40 @@ public final class com/facebook/react/fabric/FabricUIManagerProviderImpl : com/f public fun createUIManager (Lcom/facebook/react/bridge/ReactApplicationContext;)Lcom/facebook/react/bridge/UIManager; } -public class com/facebook/react/fabric/mounting/SurfaceMountingManager { - public static final field TAG Ljava/lang/String; - public fun (ILcom/facebook/react/touch/JSResponderHandler;Lcom/facebook/react/uimanager/ViewManagerRegistry;Lcom/facebook/react/uimanager/RootViewManager;Lcom/facebook/react/fabric/mounting/MountingManager$MountItemExecutor;Lcom/facebook/react/uimanager/ThemedReactContext;)V - public fun addViewAt (III)V - public fun attachRootView (Landroid/view/View;Lcom/facebook/react/uimanager/ThemedReactContext;)V - public fun createView (Ljava/lang/String;ILcom/facebook/react/bridge/ReadableMap;Lcom/facebook/react/uimanager/StateWrapper;Lcom/facebook/react/fabric/events/EventEmitterWrapper;Z)V - public fun createViewUnsafe (Ljava/lang/String;ILcom/facebook/react/bridge/ReadableMap;Lcom/facebook/react/uimanager/StateWrapper;Lcom/facebook/react/fabric/events/EventEmitterWrapper;Z)V - public fun deleteView (I)V - public fun enqueuePendingEvent (ILjava/lang/String;ZLcom/facebook/react/bridge/WritableMap;I)V - public fun getContext ()Lcom/facebook/react/uimanager/ThemedReactContext; - public fun getEventEmitter (I)Lcom/facebook/react/fabric/events/EventEmitterWrapper; - public fun getSurfaceId ()I - public fun getView (I)Landroid/view/View; - public fun getViewExists (I)Z - public fun isRootViewAttached ()Z - public fun isStopped ()Z - public fun markActiveTouchForTag (I)V - public fun preallocateView (Ljava/lang/String;ILcom/facebook/react/bridge/ReadableMap;Lcom/facebook/react/uimanager/StateWrapper;Z)V - public fun printSurfaceState ()V - public fun receiveCommand (IILcom/facebook/react/bridge/ReadableArray;)V - public fun receiveCommand (ILjava/lang/String;Lcom/facebook/react/bridge/ReadableArray;)V - public fun removeViewAt (III)V - public fun scheduleMountItemOnViewAttach (Lcom/facebook/react/fabric/mounting/mountitems/MountItem;)V - public fun sendAccessibilityEvent (II)V - public fun setJSResponder (IIZ)V - public fun stopSurface ()V - public fun storeSynchronousMountPropsOverride (ILcom/facebook/react/bridge/ReadableMap;)V - public fun sweepActiveTouchForTag (I)V - public fun updateEventEmitter (ILcom/facebook/react/fabric/events/EventEmitterWrapper;)V - public fun updateLayout (IIIIIIII)V - public fun updateOverflowInset (IIIII)V - public fun updatePadding (IIIII)V - public fun updateProps (ILcom/facebook/react/bridge/ReadableMap;)V - public fun updatePropsSynchronously (ILcom/facebook/react/bridge/ReadableMap;)V - public fun updateState (ILcom/facebook/react/uimanager/StateWrapper;)V +public final class com/facebook/react/fabric/mounting/SurfaceMountingManager { + public static final field Companion Lcom/facebook/react/fabric/mounting/SurfaceMountingManager$Companion; + public final fun addViewAt (III)V + public final fun attachRootView (Landroid/view/View;Lcom/facebook/react/uimanager/ThemedReactContext;)V + public final fun deleteView (I)V + public final fun enqueuePendingEvent (ILjava/lang/String;ZLcom/facebook/react/bridge/WritableMap;I)V + public final fun getContext ()Lcom/facebook/react/uimanager/ThemedReactContext; + public final fun getSurfaceId ()I + public static final fun getTAG ()Ljava/lang/String; + public final fun getView (I)Landroid/view/View; + public final fun getViewExists (I)Z + public final fun isRootViewAttached ()Z + public final fun isStopped ()Z + public final fun markActiveTouchForTag (I)V + public final fun preallocateView (Ljava/lang/String;ILcom/facebook/react/bridge/ReadableMap;Lcom/facebook/react/uimanager/StateWrapper;Z)V + public final fun printSurfaceState ()V + public final fun receiveCommand (IILcom/facebook/react/bridge/ReadableArray;)V + public final fun receiveCommand (ILjava/lang/String;Lcom/facebook/react/bridge/ReadableArray;)V + public final fun removeViewAt (III)V + public final fun sendAccessibilityEvent (II)V + public final fun setJSResponder (IIZ)V + public final fun stopSurface ()V + public final fun storeSynchronousMountPropsOverride (ILcom/facebook/react/bridge/ReadableMap;)V + public final fun sweepActiveTouchForTag (I)V + public final fun updateLayout (IIIIIIII)V + public final fun updateOverflowInset (IIIII)V + public final fun updatePadding (IIIII)V + public final fun updateProps (ILcom/facebook/react/bridge/ReadableMap;)V + public final fun updatePropsSynchronously (ILcom/facebook/react/bridge/ReadableMap;)V + public final fun updateState (ILcom/facebook/react/uimanager/StateWrapper;)V +} + +public final class com/facebook/react/fabric/mounting/SurfaceMountingManager$Companion { + public final fun getTAG ()Ljava/lang/String; } public abstract interface class com/facebook/react/interfaces/TaskInterface { diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/fabric/FabricUIManager.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/fabric/FabricUIManager.java index a4cb1c2dd5ed47..83467522bdd23b 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/fabric/FabricUIManager.java +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/fabric/FabricUIManager.java @@ -824,8 +824,8 @@ public void synchronouslyUpdateViewOnUIThread(final int reactTag, final Readable private void preallocateView( int rootTag, int reactTag, - final String componentName, - @Nullable Object props, + String componentName, + Object props, @Nullable Object stateWrapper, boolean isLayoutable) { mMountItemDispatcher.addPreAllocateMountItem( diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/fabric/mounting/MountingManager.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/fabric/mounting/MountingManager.kt index c40beec2172797..79ec6d2e8f9be9 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/fabric/mounting/MountingManager.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/fabric/mounting/MountingManager.kt @@ -99,7 +99,7 @@ internal class MountingManager( } @AnyThread - fun attachRootView(surfaceId: Int, rootView: View?, themedReactContext: ThemedReactContext?) { + fun attachRootView(surfaceId: Int, rootView: View, themedReactContext: ThemedReactContext) { val surfaceMountingManager = getSurfaceManagerEnforced(surfaceId, "attachView") if (surfaceMountingManager.isStopped) { @@ -336,7 +336,7 @@ internal class MountingManager( fun enqueuePendingEvent( surfaceId: Int, reactTag: Int, - eventName: String?, + eventName: String, canCoalesceEvent: Boolean, params: WritableMap?, @EventCategoryDef eventCategory: Int, diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/fabric/mounting/SurfaceMountingManager.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/fabric/mounting/SurfaceMountingManager.java deleted file mode 100644 index 23e9e5efb116f7..00000000000000 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/fabric/mounting/SurfaceMountingManager.java +++ /dev/null @@ -1,1411 +0,0 @@ -/* - * 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. - */ - -package com.facebook.react.fabric.mounting; - -import static com.facebook.infer.annotation.ThreadConfined.ANY; -import static com.facebook.infer.annotation.ThreadConfined.UI; - -import android.annotation.SuppressLint; -import android.view.View; -import android.view.ViewGroup; -import android.view.ViewParent; -import androidx.annotation.AnyThread; -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.annotation.UiThread; -import androidx.collection.SparseArrayCompat; -import com.facebook.common.logging.FLog; -import com.facebook.infer.annotation.Assertions; -import com.facebook.infer.annotation.ThreadConfined; -import com.facebook.react.bridge.GuardedRunnable; -import com.facebook.react.bridge.ReactNoCrashSoftException; -import com.facebook.react.bridge.ReactSoftExceptionLogger; -import com.facebook.react.bridge.ReadableArray; -import com.facebook.react.bridge.ReadableMap; -import com.facebook.react.bridge.ReadableType; -import com.facebook.react.bridge.RetryableMountingLayerException; -import com.facebook.react.bridge.SoftAssertions; -import com.facebook.react.bridge.UiThreadUtil; -import com.facebook.react.bridge.WritableArray; -import com.facebook.react.bridge.WritableMap; -import com.facebook.react.bridge.WritableNativeArray; -import com.facebook.react.bridge.WritableNativeMap; -import com.facebook.react.common.annotations.UnstableReactNativeAPI; -import com.facebook.react.common.build.ReactBuildConfig; -import com.facebook.react.common.mapbuffer.MapBuffer; -import com.facebook.react.fabric.events.EventEmitterWrapper; -import com.facebook.react.fabric.mounting.MountingManager.MountItemExecutor; -import com.facebook.react.fabric.mounting.mountitems.MountItem; -import com.facebook.react.internal.featureflags.ReactNativeFeatureFlags; -import com.facebook.react.touch.JSResponderHandler; -import com.facebook.react.uimanager.IViewGroupManager; -import com.facebook.react.uimanager.IllegalViewOperationException; -import com.facebook.react.uimanager.ReactOverflowViewWithInset; -import com.facebook.react.uimanager.ReactRoot; -import com.facebook.react.uimanager.ReactStylesDiffMap; -import com.facebook.react.uimanager.RootView; -import com.facebook.react.uimanager.RootViewManager; -import com.facebook.react.uimanager.StateWrapper; -import com.facebook.react.uimanager.ThemedReactContext; -import com.facebook.react.uimanager.ViewManager; -import com.facebook.react.uimanager.ViewManagerRegistry; -import com.facebook.react.uimanager.events.EventCategoryDef; -import com.facebook.systrace.Systrace; -import java.util.ArrayDeque; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.Map; -import java.util.Queue; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; - -public class SurfaceMountingManager { - public static final String TAG = SurfaceMountingManager.class.getSimpleName(); - - private static final boolean SHOW_CHANGED_VIEW_HIERARCHIES = ReactBuildConfig.DEBUG && false; - private static final String PROP_TRANSFORM = "transform"; - private static final String PROP_OPACITY = "opacity"; - - private volatile boolean mIsStopped = false; - private volatile boolean mRootViewAttached = false; - - @Nullable private ThemedReactContext mThemedReactContext; - - // These are all non-null, until StopSurface is called - private ConcurrentHashMap mTagToViewState = - new ConcurrentHashMap<>(); // any thread - private final Queue mOnViewAttachMountItems = new ArrayDeque<>(); - private JSResponderHandler mJSResponderHandler; - private final ViewManagerRegistry mViewManagerRegistry; - private RootViewManager mRootViewManager; - private MountItemExecutor mMountItemExecutor; - - @ThreadConfined(UI) - private final Set mErroneouslyReaddedReactTags = new HashSet<>(); - - // This set is used to keep track of views that are currently being interacted with (i.e. - // views that saw a ACTION_DOWN but not a ACTION_UP event yet). This is used to prevent - // views from being removed while they are being interacted with as their event emitter will - // also be removed, and `Pressables` will look "stuck". - @ThreadConfined(UI) - private final Set mViewsWithActiveTouches = new HashSet<>(); - - // This set contains the views that are scheduled to be removed after their touch finishes. - @ThreadConfined(UI) - private final Set mViewsToDeleteAfterTouchFinishes = new HashSet<>(); - - // This is null *until* StopSurface is called. - private SparseArrayCompat mTagSetForStoppedSurface; - - // This is to make sure direct manipulation result will not be overridden by React update. - @ThreadConfined(UI) - private final SparseArrayCompat> mTagToSynchronousMountProps = - new SparseArrayCompat<>(); - - private final int mSurfaceId; - - public SurfaceMountingManager( - int surfaceId, - @NonNull JSResponderHandler jsResponderHandler, - @NonNull ViewManagerRegistry viewManagerRegistry, - @NonNull RootViewManager rootViewManager, - @NonNull MountItemExecutor mountItemExecutor, - @NonNull ThemedReactContext reactContext) { - mSurfaceId = surfaceId; - mJSResponderHandler = jsResponderHandler; - mViewManagerRegistry = viewManagerRegistry; - mRootViewManager = rootViewManager; - mMountItemExecutor = mountItemExecutor; - mThemedReactContext = reactContext; - } - - public boolean isStopped() { - return mIsStopped; - } - - public void attachRootView(View rootView, ThemedReactContext themedReactContext) { - mThemedReactContext = themedReactContext; - addRootView(rootView); - } - - public int getSurfaceId() { - return mSurfaceId; - } - - public boolean isRootViewAttached() { - return mRootViewAttached; - } - - @Nullable - public ThemedReactContext getContext() { - return mThemedReactContext; - } - - private static void logViewHierarchy(ViewGroup parent, boolean recurse) { - int parentTag = parent.getId(); - FLog.e(TAG, " "); - for (int i = 0; i < parent.getChildCount(); i++) { - FLog.e( - TAG, - " "); - } - FLog.e(TAG, " "); - - if (recurse) { - FLog.e(TAG, "Displaying Ancestors:"); - ViewParent ancestor = parent.getParent(); - while (ancestor != null) { - ViewGroup ancestorViewGroup = (ancestor instanceof ViewGroup ? (ViewGroup) ancestor : null); - int ancestorId = ancestorViewGroup == null ? View.NO_ID : ancestorViewGroup.getId(); - FLog.e( - TAG, - ""); - ancestor = ancestor.getParent(); - } - } - } - - public boolean getViewExists(int tag) { - // If Surface stopped, check if tag *was* associated with this Surface, even though it's been - // deleted. This helps distinguish between scenarios where an invalid tag is referenced, vs - // race conditions where an imperative method is called on a tag during/just after StopSurface. - if (mTagSetForStoppedSurface != null && mTagSetForStoppedSurface.containsKey(tag)) { - return true; - } - if (mTagToViewState == null) { - return false; - } - return mTagToViewState.containsKey(tag); - } - - @UiThread - @ThreadConfined(UI) - public void scheduleMountItemOnViewAttach(MountItem item) { - mOnViewAttachMountItems.add(item); - } - - @AnyThread - private void addRootView(@NonNull final View rootView) { - if (isStopped()) { - return; - } - - mTagToViewState.put(mSurfaceId, new ViewState(mSurfaceId, rootView, mRootViewManager, true)); - - Runnable runnable = - new GuardedRunnable(Assertions.assertNotNull(mThemedReactContext)) { - @Override - public void runGuarded() { - // The CPU has ticked since `addRootView` was called, so the surface could technically - // have already stopped here. - if (isStopped()) { - return; - } - - if (rootView.getId() == mSurfaceId) { - ReactSoftExceptionLogger.logSoftException( - TAG, - new IllegalViewOperationException( - "Race condition in addRootView detected. Trying to set an id of [" - + mSurfaceId - + "] on the RootView, but that id has already been set. ")); - } else if (rootView.getId() != View.NO_ID) { - FLog.e( - TAG, - "Trying to add RootTag to RootView that already has a tag: existing tag: [%d] new" - + " tag: [%d]", - rootView.getId(), - mSurfaceId); - // This behavior can not be guaranteed in hybrid apps that have a native android layer - // over which reactRootViews are added and the native views need to have ids on them - // in order to work. Hence this can cause unnecessary crashes at runtime for hybrid - // apps. So converting this to a soft exception such that pure react-native devs can - // still see the warning while hybrid apps continue to run without crashes - ReactSoftExceptionLogger.logSoftException( - TAG, - new IllegalViewOperationException( - "Trying to add a root view with an explicit id already set. React Native uses" - + " the id field to track react tags and will overwrite this field. If" - + " that is fine, explicitly overwrite the id field to View.NO_ID before" - + " calling addRootView.")); - } - rootView.setId(mSurfaceId); - - if (rootView instanceof ReactRoot) { - ((ReactRoot) rootView).setRootViewTag(mSurfaceId); - } - - executeMountItemsOnViewAttach(); - - // By doing this after `executeMountItemsOnViewAttach`, we ensure that any operations - // scheduled while processing this queue are also added to the queue, instead of being - // processed immediately through the queue in `MountItemDispatcher`. - mRootViewAttached = true; - } - }; - - if (UiThreadUtil.isOnUiThread()) { - runnable.run(); - } else { - UiThreadUtil.runOnUiThread(runnable); - } - } - - @UiThread - @ThreadConfined(UI) - private void executeMountItemsOnViewAttach() { - mMountItemExecutor.executeItems(mOnViewAttachMountItems); - } - - /** - * Stop surface and all operations within it. Garbage-collect Views (caller is responsible for - * removing RootView from View layer). - * - *

Delete rootView from cache. Since RN does not control the RootView, in a sense, the fragment - * is responsible for actually removing the RootView from the hierarchy / tearing down the - * fragment. - * - *

In the original version(s) of this function, we recursively went through all children of the - * View and dropped those Views as well; ad infinitum. This was before we had a - * SurfaceMountingManager, and all tags were in one global map. Doing this was particularly - * important in the case of StopSurface, where race conditions between threads meant you couldn't - * rely on DELETE instructions actually deleting all Views in the Surface. - * - *

Now that we have SurfaceMountingManager, we can simply drop our local reference to the View. - * Since it will be removed from the View hierarchy entirely (outside of the scope of this class), - * garbage collection will take care of destroying it and all descendents. - */ - @AnyThread - public void stopSurface() { - FLog.e(TAG, "Stopping surface [" + mSurfaceId + "]"); - if (isStopped()) { - return; - } - - // Prevent more views from being created, or the hierarchy from being manipulated at all. This - // causes further operations to noop. - mIsStopped = true; - - // Reset all StateWrapper objects - // Since this can happen on any thread, is it possible to race between StateWrapper destruction - // and some accesses from View classes in the UI thread? - for (ViewState viewState : mTagToViewState.values()) { - if (viewState.mStateWrapper != null) { - viewState.mStateWrapper.destroyState(); - viewState.mStateWrapper = null; - } - if (viewState.mEventEmitter != null) { - viewState.mEventEmitter.destroy(); - viewState.mEventEmitter = null; - } - } - - Runnable runnable = - () -> { - if (ReactNativeFeatureFlags.enableViewRecycling()) { - mViewManagerRegistry.onSurfaceStopped(mSurfaceId); - } - mTagSetForStoppedSurface = new SparseArrayCompat<>(); - for (Map.Entry entry : mTagToViewState.entrySet()) { - // Using this as a placeholder value in the map. We're using SparseArrayCompat - // since it can efficiently represent the list of pending tags - mTagSetForStoppedSurface.put(entry.getKey(), this); - - // We must call `onDropViewInstance` on all remaining Views - onViewStateDeleted(entry.getValue()); - } - - // Evict all views from cache and memory - // TODO: clear instead of nulling out to simplify null-safety in this class - mTagToViewState = null; - mJSResponderHandler = null; - mRootViewManager = null; - mMountItemExecutor = null; - mThemedReactContext = null; - mOnViewAttachMountItems.clear(); - mTagToSynchronousMountProps.clear(); - - FLog.e(TAG, "Surface [" + mSurfaceId + "] was stopped on SurfaceMountingManager."); - }; - - if (UiThreadUtil.isOnUiThread()) { - runnable.run(); - } else { - UiThreadUtil.runOnUiThread(runnable); - } - } - - @UiThread - public void addViewAt(final int parentTag, final int tag, final int index) { - UiThreadUtil.assertOnUiThread(); - if (isStopped()) { - return; - } - - ViewState parentViewState = getViewState(parentTag); - if (!(parentViewState.mView instanceof ViewGroup)) { - String message = - "Unable to add a view into a view that is not a ViewGroup. ParentTag: " - + parentTag - + " - Tag: " - + tag - + " - Index: " - + index; - FLog.e(TAG, message); - throw new IllegalStateException(message); - } - final ViewGroup parentView = (ViewGroup) parentViewState.mView; - ViewState viewState = getViewState(tag); - final View view = viewState.mView; - if (view == null) { - throw new IllegalStateException( - "Unable to find view for viewState " + viewState + " and tag " + tag); - } - - // Display children before inserting - if (SHOW_CHANGED_VIEW_HIERARCHIES) { - FLog.e(TAG, "addViewAt: [" + tag + "] -> [" + parentTag + "] idx: " + index + " BEFORE"); - logViewHierarchy(parentView, false); - } - - ViewParent viewParent = view.getParent(); - if (viewParent != null) { - int actualParentId = - viewParent instanceof ViewGroup ? ((ViewGroup) viewParent).getId() : View.NO_ID; - ReactSoftExceptionLogger.logSoftException( - TAG, - new IllegalStateException( - "addViewAt: cannot insert view [" - + tag - + "] into parent [" - + parentTag - + "]: View already has a parent: [" - + actualParentId - + "] " - + " Parent: " - + viewParent.getClass().getSimpleName() - + " View: " - + view.getClass().getSimpleName())); - - // We've hit an error case, and `addView` will crash below - // if we don't take evasive action (it is an error to add a View - // to the hierarchy if it already has a parent). - // We don't know /why/ this happens yet, but it does happen - // very infrequently in production. - // Thus, we do three things here: - // (1) We logged a SoftException above, so if there's a crash later - // on, we might have some hints about what caused it. - // (2) We remove the View from its parent. - // (3) In case the View was removed from the hierarchy with the - // RemoveDeleteTree instruction, and is now being readded - which - // should be impossible - we mark this as a "readded" View and - // thus prevent the RemoveDeleteTree worker from deleting this - // View in the future. - if (viewParent instanceof ViewGroup) { - ((ViewGroup) viewParent).removeView(view); - } - mErroneouslyReaddedReactTags.add(tag); - } - - try { - getViewGroupManager(parentViewState).addView(parentView, view, index); - } catch (IllegalStateException | IndexOutOfBoundsException e) { - // Wrap error with more context for debugging - throw new IllegalStateException( - "addViewAt: failed to insert view [" - + tag - + "] into parent [" - + parentTag - + "] at index " - + index, - e); - } - - // Display children after inserting - if (SHOW_CHANGED_VIEW_HIERARCHIES) { - // Why are we calling `runOnUiThread`? We're already on the UI thread, right?! - // Yes - but if you get the children of the View here and display them, *it might show you - // the previous children*. Without getting too much into Android internals, basically if we - // wait a tick, everything is what we expect. - // tldr is that `parent.children == []; parent.addView(x); parent.children == []` - // and you need to wait a tick for `parent.children == [x]`. - UiThreadUtil.runOnUiThread( - new Runnable() { - @Override - public void run() { - FLog.e( - TAG, "addViewAt: [" + tag + "] -> [" + parentTag + "] idx: " + index + " AFTER"); - logViewHierarchy(parentView, false); - } - }); - } - } - - @UiThread - public void removeViewAt(final int tag, final int parentTag, int index) { - if (isStopped()) { - return; - } - - // This is "impossible". See comments above. - if (mErroneouslyReaddedReactTags.contains(tag)) { - ReactSoftExceptionLogger.logSoftException( - TAG, - new IllegalViewOperationException( - "removeViewAt tried to remove a React View that was actually reused. This indicates a" - + " bug in the Differ (specifically instruction ordering). [" - + tag - + "]")); - return; - } - - UiThreadUtil.assertOnUiThread(); - ViewState parentViewState = getNullableViewState(parentTag); - - // TODO: throw exception here? - if (parentViewState == null) { - ReactSoftExceptionLogger.logSoftException( - ReactSoftExceptionLogger.Categories.SURFACE_MOUNTING_MANAGER_MISSING_VIEWSTATE, - new IllegalStateException( - "Unable to find viewState for tag: [" + parentTag + "] for removeViewAt")); - return; - } - - if (!(parentViewState.mView instanceof ViewGroup)) { - String message = - "Unable to remove a view from a view that is not a ViewGroup. ParentTag: " - + parentTag - + " - Tag: " - + tag - + " - Index: " - + index; - FLog.e(TAG, message); - throw new IllegalStateException(message); - } - - final ViewGroup parentView = (ViewGroup) parentViewState.mView; - - if (parentView == null) { - throw new IllegalStateException("Unable to find view for tag [" + parentTag + "]"); - } - - if (SHOW_CHANGED_VIEW_HIERARCHIES) { - // Display children before deleting any - FLog.e(TAG, "removeViewAt: [" + tag + "] -> [" + parentTag + "] idx: " + index + " BEFORE"); - logViewHierarchy(parentView, false); - } - - IViewGroupManager viewGroupManager = getViewGroupManager(parentViewState); - - // Verify that the view we're about to remove has the same tag we expect - View view = viewGroupManager.getChildAt(parentView, index); - int actualTag = (view != null ? view.getId() : -1); - if (actualTag != tag) { - int tagActualIndex = -1; - int parentChildrenCount = parentView.getChildCount(); - for (int i = 0; i < parentChildrenCount; i++) { - if (parentView.getChildAt(i).getId() == tag) { - tagActualIndex = i; - break; - } - } - - // TODO T74425739: previously, we did not do this check and `removeViewAt` would be executed - // below, sometimes crashing there. *However*, interestingly enough, `removeViewAt` would not - // complain if you removed views from an already-empty parent. This seems necessary currently - // for certain ViewManagers that remove their own children - like BottomSheet? - // This workaround seems not-great, but for now, we just return here for - // backwards-compatibility. Essentially, if a view has already been removed from the - // hierarchy, we treat it as a noop. - if (tagActualIndex == -1) { - FLog.e( - TAG, - "removeViewAt: [" - + tag - + "] -> [" - + parentTag - + "] @" - + index - + ": view already removed from parent! Children in parent: " - + parentChildrenCount); - return; - } - - // Here we are guaranteed that the view is still in the View hierarchy, just - // at a different index. In debug mode we'll crash here; in production, we'll remove - // the child from the parent and move on. - // This is an issue that is safely recoverable 95% of the time. If this allows corruption - // of the view hierarchy and causes bugs or a crash after this point, there will be logs - // indicating that this happened. - // This is likely *only* necessary because of Fabric's LayoutAnimations implementation. - // If we can fix the bug there, or remove the need for LayoutAnimation index adjustment - // entirely, we can just throw this exception without regression user experience. - logViewHierarchy(parentView, true); - ReactSoftExceptionLogger.logSoftException( - TAG, - new IllegalStateException( - "Tried to remove view [" - + tag - + "] of parent [" - + parentTag - + "] at index " - + index - + ", but got view tag " - + actualTag - + " - actual index of view: " - + tagActualIndex)); - index = tagActualIndex; - } - - try { - viewGroupManager.removeViewAt(parentView, index); - } catch (RuntimeException e) { - // Note: `getChildCount` may not always be accurate! - // We don't currently have a good explanation other than, in situations where you - // would empirically expect to see childCount > 0, the childCount is reported as 0. - // This is likely due to a ViewManager overriding getChildCount or some other methods - // in a way that is strictly incorrect, but potentially only visible here. - // The failure mode is actually that in `removeViewAt`, a NullPointerException is - // thrown when we try to perform an operation on a View that doesn't exist, and - // is therefore null. - // We try to add some extra diagnostics here, but we always try to remove the View - // from the hierarchy first because detecting by looking at childCount will not work. - // - // Note that the lesson here is that `getChildCount` is not /required/ to adhere to - // any invariants. If you add 9 children to a parent, the `getChildCount` of the parent - // may not be equal to 9. This apparently causes no issues with Android and is common - // enough that we shouldn't try to change this invariant, without a lot of thought. - int childCount = viewGroupManager.getChildCount(parentView); - - logViewHierarchy(parentView, true); - - throw new IllegalStateException( - "Cannot remove child at index " - + index - + " from parent ViewGroup [" - + parentView.getId() - + "], only " - + childCount - + " children in parent. Warning: childCount may be incorrect!", - e); - } - - // Display children after deleting any - if (SHOW_CHANGED_VIEW_HIERARCHIES) { - final int finalIndex = index; - UiThreadUtil.runOnUiThread( - new Runnable() { - @Override - public void run() { - FLog.e( - TAG, - "removeViewAt: [" - + tag - + "] -> [" - + parentTag - + "] idx: " - + finalIndex - + " AFTER"); - logViewHierarchy(parentView, false); - } - }); - } - } - - @UiThread - public void createView( - @NonNull String componentName, - int reactTag, - @Nullable ReadableMap props, - @Nullable StateWrapper stateWrapper, - @Nullable EventEmitterWrapper eventEmitterWrapper, - boolean isLayoutable) { - if (isStopped()) { - return; - } - // We treat this as a perf problem and not a logical error. View Preallocation or unexpected - // changes to Differ or C++ Binding could cause some redundant Create instructions. - // There are cases where preallocation happens and a node is recreated: if a node is - // preallocated and then committed with revision 2+, an extra CREATE instruction will be - // generated. - // This represents a perf issue only, not a correctness issue. In the future we need to - // refactor View preallocation to correct the currently incorrect assumptions. - ViewState viewState = getNullableViewState(reactTag); - if (viewState != null && viewState.mView != null) { - return; - } - - createViewUnsafe( - componentName, reactTag, props, stateWrapper, eventEmitterWrapper, isLayoutable); - } - - /** - * Perform view creation without any safety checks. You must ensure safety before calling this - * method (see existing callsites). - * - * @param componentName - * @param reactTag - * @param props - * @param stateWrapper - * @param eventEmitterWrapper - * @param isLayoutable - */ - @UiThread - public void createViewUnsafe( - @NonNull String componentName, - int reactTag, - @Nullable ReadableMap props, - @Nullable StateWrapper stateWrapper, - @Nullable EventEmitterWrapper eventEmitterWrapper, - boolean isLayoutable) { - Systrace.beginSection( - Systrace.TRACE_TAG_REACT, - "SurfaceMountingManager::createViewUnsafe(" + componentName + ")"); - try { - ReactStylesDiffMap propMap = new ReactStylesDiffMap(props); - - ViewState viewState = new ViewState(reactTag); - viewState.mCurrentProps = propMap; - viewState.mStateWrapper = stateWrapper; - viewState.mEventEmitter = eventEmitterWrapper; - mTagToViewState.put(reactTag, viewState); - - if (isLayoutable) { - ViewManager viewManager = mViewManagerRegistry.get(componentName); - // View Managers are responsible for dealing with inital state and props. - viewState.mView = - viewManager.createView( - reactTag, mThemedReactContext, propMap, stateWrapper, mJSResponderHandler); - viewState.mViewManager = viewManager; - } - } finally { - Systrace.endSection(Systrace.TRACE_TAG_REACT); - } - } - - private static void overridePropsReadableMap( - Map patchMap, WritableMap outputReadableMap) { - for (Map.Entry entry : patchMap.entrySet()) { - String propKey = entry.getKey(); - if (outputReadableMap.hasKey(propKey)) { - Object propValue = entry.getValue(); - if (propKey.equals(PROP_TRANSFORM)) { - assert (outputReadableMap.getType(propKey) == ReadableType.Array - && propValue instanceof ArrayList); - WritableArray array = new WritableNativeArray(); - for (Object item : (ArrayList) propValue) { - if (item instanceof HashMap) { - WritableNativeMap itemMap = new WritableNativeMap(); - for (Map.Entry itemEntry : - ((HashMap) item).entrySet()) { - if (itemEntry.getValue() instanceof String) { - itemMap.putString(itemEntry.getKey(), (String) itemEntry.getValue()); - } else if (itemEntry.getValue() instanceof Number) { - itemMap.putDouble( - itemEntry.getKey(), ((Number) itemEntry.getValue()).doubleValue()); - } - } - array.pushMap(itemMap); - } - } - outputReadableMap.putArray(propKey, array); - } else if (propKey.equals(PROP_OPACITY)) { - assert (outputReadableMap.getType(propKey) == ReadableType.Number - && propValue instanceof Number); - outputReadableMap.putDouble(propKey, ((Number) propValue).doubleValue()); - } - } - } - } - - private static Map getHashMapFromPropsReadableMap(ReadableMap readableMap) { - HashMap outputMap = new HashMap<>(); - - if (readableMap.hasKey(PROP_TRANSFORM) - && readableMap.getType(PROP_TRANSFORM) == ReadableType.Array) { - ReadableArray transformArray = readableMap.getArray(PROP_TRANSFORM); - if (transformArray != null) { - ArrayList> arrayList = new ArrayList<>(transformArray.size()); - for (int i = 0; i < transformArray.size(); i++) { - ReadableMap map = transformArray.getMap(i); - if (map != null) { - arrayList.add(map.toHashMap()); - } - } - outputMap.put(PROP_TRANSFORM, arrayList); - } - } - - if (readableMap.hasKey(PROP_OPACITY) - && readableMap.getType(PROP_OPACITY) == ReadableType.Number) { - outputMap.put(PROP_OPACITY, readableMap.getDouble(PROP_OPACITY)); - } - - return outputMap; - } - - public void storeSynchronousMountPropsOverride(int reactTag, ReadableMap props) { - if (ReactNativeFeatureFlags.overrideBySynchronousMountPropsAtMountingAndroid()) { - Map propsMap = getHashMapFromPropsReadableMap(props); - if (mTagToSynchronousMountProps.containsKey(reactTag)) { - Map mergedPropsMap = - Assertions.assertNotNull(mTagToSynchronousMountProps.get(reactTag)); - mergedPropsMap.putAll(propsMap); - mTagToSynchronousMountProps.put(reactTag, mergedPropsMap); - } else { - mTagToSynchronousMountProps.put(reactTag, propsMap); - } - } - } - - public void updatePropsSynchronously(int reactTag, ReadableMap props) { - updateProps(reactTag, props, true); - } - - public void updateProps(int reactTag, ReadableMap props) { - updateProps(reactTag, props, false); - } - - @UiThread - private void updateProps( - int reactTag, ReadableMap props, Boolean shouldSkipSynchronousMountPropsOverride) { - if (isStopped()) { - return; - } - - ViewState viewState = getViewState(reactTag); - - if (ReactNativeFeatureFlags.overrideBySynchronousMountPropsAtMountingAndroid() - && !shouldSkipSynchronousMountPropsOverride - && mTagToSynchronousMountProps.containsKey(reactTag)) { - WritableMap modifiedProps = new WritableNativeMap(); - modifiedProps.merge(props); - Map directPropsMap = - Assertions.assertNotNull(mTagToSynchronousMountProps.get(reactTag)); - overridePropsReadableMap(directPropsMap, modifiedProps); - viewState.mCurrentProps = new ReactStylesDiffMap(modifiedProps); - } else { - viewState.mCurrentProps = new ReactStylesDiffMap(props); - } - - View view = viewState.mView; - - if (view == null) { - throw new IllegalStateException("Unable to find view for tag [" + reactTag + "]"); - } - - Assertions.assertNotNull(viewState.mViewManager) - .updateProperties(view, viewState.mCurrentProps); - } - - /** - * This prefetch method is experimental, do not use it for production code. it will most likely - * change or be removed in the future. - * - * @param surfaceId surface ID - * @param componentName - * @param params prefetch request params defined in C++ - */ - @SuppressLint("FunctionName") - @AnyThread - @UnstableReactNativeAPI - public void experimental_prefetchResources( - int surfaceId, String componentName, MapBuffer params) { - if (isStopped()) { - return; - } - mViewManagerRegistry - .get(componentName) - .experimental_prefetchResources( - surfaceId, Assertions.assertNotNull(mThemedReactContext), params); - } - - @Deprecated - public void receiveCommand(int reactTag, int commandId, ReadableArray commandArgs) { - if (isStopped()) { - return; - } - - ViewState viewState = getNullableViewState(reactTag); - - // It's not uncommon for JS to send events as/after a component is being removed from the - // view hierarchy. For example, TextInput may send a "blur" command in response to the view - // disappearing. Throw `ReactNoCrashSoftException` so they're logged but don't crash in dev - // for now. - if (viewState == null) { - throw new RetryableMountingLayerException( - "Unable to find viewState for tag: [" + reactTag + "] for commandId: " + commandId); - } - - if (viewState.mViewManager == null) { - throw new RetryableMountingLayerException("Unable to find viewManager for tag " + reactTag); - } - - if (viewState.mView == null) { - throw new RetryableMountingLayerException( - "Unable to find viewState view for tag " + reactTag); - } - - viewState.mViewManager.receiveCommand(viewState.mView, commandId, commandArgs); - } - - public void receiveCommand(int reactTag, @NonNull String commandId, ReadableArray commandArgs) { - if (isStopped()) { - return; - } - - ViewState viewState = getNullableViewState(reactTag); - - // It's not uncommon for JS to send events as/after a component is being removed from the - // view hierarchy. For example, TextInput may send a "blur" command in response to the view - // disappearing. Throw `ReactNoCrashSoftException` so they're logged but don't crash in dev - // for now. - if (viewState == null) { - throw new RetryableMountingLayerException( - "Unable to find viewState for tag: " + reactTag + " for commandId: " + commandId); - } - - if (viewState.mViewManager == null) { - throw new RetryableMountingLayerException( - "Unable to find viewState manager for tag " + reactTag); - } - - if (viewState.mView == null) { - throw new RetryableMountingLayerException( - "Unable to find viewState view for tag " + reactTag); - } - - viewState.mViewManager.receiveCommand(viewState.mView, commandId, commandArgs); - } - - public void sendAccessibilityEvent(int reactTag, int eventType) { - if (isStopped()) { - return; - } - - ViewState viewState = getViewState(reactTag); - - if (viewState.mViewManager == null) { - throw new RetryableMountingLayerException( - "Unable to find viewState manager for tag " + reactTag); - } - - if (viewState.mView == null) { - throw new RetryableMountingLayerException( - "Unable to find viewState view for tag " + reactTag); - } - - viewState.mView.sendAccessibilityEvent(eventType); - } - - @UiThread - public void updateLayout( - int reactTag, - int parentTag, - int x, - int y, - int width, - int height, - int displayType, - int layoutDirection) { - if (isStopped()) { - return; - } - - ViewState viewState = getViewState(reactTag); - // Do not layout Root Views - if (viewState.mIsRoot) { - return; - } - - View viewToUpdate = viewState.mView; - if (viewToUpdate == null) { - throw new IllegalStateException("Unable to find View for tag: " + reactTag); - } - - viewToUpdate.setLayoutDirection( - layoutDirection == 1 - ? View.LAYOUT_DIRECTION_LTR - : layoutDirection == 2 ? View.LAYOUT_DIRECTION_RTL : View.LAYOUT_DIRECTION_INHERIT); - - // Even though we have exact dimensions, we still call measure because some platform views (e.g. - // Switch) assume that method will always be called before onLayout and onDraw. They use it to - // calculate and cache information used in the draw pass. For most views, onMeasure can be - // stubbed out to only call setMeasuredDimensions. For ViewGroups, onLayout should be stubbed - // out to not recursively call layout on its children: React Native already handles doing - // that. - // - // Also, note measure and layout need to be called *after* all View properties have been updated - // because of caching and calculation that may occur in onMeasure and onLayout. Layout - // operations should also follow the native view hierarchy and go top to bottom for - // consistency with standard layout passes (some views may depend on this). - viewToUpdate.measure( - View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.EXACTLY), - View.MeasureSpec.makeMeasureSpec(height, View.MeasureSpec.EXACTLY)); - - // We update the layout of the RootView when there is a change in the layout of its child. This - // is required to re-measure the size of the native View container (usually a FrameLayout) that - // is configured with layout_height = WRAP_CONTENT or layout_width = WRAP_CONTENT - // - // This code is going to be executed ONLY when there is a change in the size of the root view - // defined in the JS side. Changes in the layout of inner views will not trigger an update on - // the layout of the root view. - ViewParent parent = viewToUpdate.getParent(); - if (parent instanceof RootView) { - parent.requestLayout(); - } - - // TODO T212247085: Make this non-nullable again after rolling out - // disableMountItemReorderingAndroid - ViewState parentViewState = getNullableViewState(parentTag); - IViewGroupManager parentViewManager = null; - if (parentViewState == null) { - ReactSoftExceptionLogger.logSoftException( - ReactSoftExceptionLogger.Categories.SURFACE_MOUNTING_MANAGER_MISSING_VIEWSTATE, - new ReactNoCrashSoftException( - "Unable to find viewState for tag: " + parentTag + " for updateLayout")); - } else if (parentViewState.mViewManager != null) { - parentViewManager = (IViewGroupManager) parentViewState.mViewManager; - } - if (parentViewManager == null || !parentViewManager.needsCustomLayoutForChildren()) { - viewToUpdate.layout(x, y, x + width, y + height); - } - - // displayType: 0 represents display: 'none' - int visibility = displayType == 0 ? View.INVISIBLE : View.VISIBLE; - if (viewToUpdate.getVisibility() != visibility) { - viewToUpdate.setVisibility(visibility); - } - } - - @UiThread - public void updatePadding(int reactTag, int left, int top, int right, int bottom) { - UiThreadUtil.assertOnUiThread(); - if (isStopped()) { - return; - } - - ViewState viewState = getViewState(reactTag); - // Do not layout Root Views - if (viewState.mIsRoot) { - return; - } - - View viewToUpdate = viewState.mView; - if (viewToUpdate == null) { - throw new IllegalStateException("Unable to find View for tag: " + reactTag); - } - - ViewManager viewManager = viewState.mViewManager; - if (viewManager == null) { - throw new IllegalStateException("Unable to find ViewManager for view: " + viewState); - } - - //noinspection unchecked - viewManager.setPadding(viewToUpdate, left, top, right, bottom); - } - - @UiThread - public void updateOverflowInset( - int reactTag, - int overflowInsetLeft, - int overflowInsetTop, - int overflowInsetRight, - int overflowInsetBottom) { - if (isStopped()) { - return; - } - - ViewState viewState = getViewState(reactTag); - // Do not layout Root Views - if (viewState.mIsRoot) { - return; - } - - View viewToUpdate = viewState.mView; - if (viewToUpdate == null) { - throw new IllegalStateException("Unable to find View for tag: " + reactTag); - } - - if (viewToUpdate instanceof ReactOverflowViewWithInset) { - ((ReactOverflowViewWithInset) viewToUpdate) - .setOverflowInset( - overflowInsetLeft, overflowInsetTop, overflowInsetRight, overflowInsetBottom); - } - } - - @UiThread - public void updateState(final int reactTag, @Nullable StateWrapper stateWrapper) { - UiThreadUtil.assertOnUiThread(); - if (isStopped()) { - return; - } - - ViewState viewState = getViewState(reactTag); - - StateWrapper prevStateWrapper = viewState.mStateWrapper; - viewState.mStateWrapper = stateWrapper; - - ViewManager viewManager = viewState.mViewManager; - - if (viewManager == null) { - throw new IllegalStateException("Unable to find ViewManager for tag: " + reactTag); - } - Object extraData = - viewManager.updateState(viewState.mView, viewState.mCurrentProps, stateWrapper); - if (extraData != null) { - viewManager.updateExtraData(viewState.mView, extraData); - } - - // Immediately clear native side of previous state wrapper. This causes the State object in C++ - // to be destroyed immediately instead of waiting for Java GC to kick in. - if (prevStateWrapper != null) { - prevStateWrapper.destroyState(); - } - } - - /** We update the event emitter from the main thread when the view is mounted. */ - @UiThread - public void updateEventEmitter(int reactTag, @NonNull EventEmitterWrapper eventEmitter) { - UiThreadUtil.assertOnUiThread(); - if (isStopped()) { - return; - } - - ViewState viewState = mTagToViewState.get(reactTag); - if (viewState == null) { - // TODO T62717437 - Use a flag to determine that these event emitters belong to virtual nodes - // only. - viewState = new ViewState(reactTag); - mTagToViewState.put(reactTag, viewState); - } - EventEmitterWrapper previousEventEmitterWrapper = viewState.mEventEmitter; - viewState.mEventEmitter = eventEmitter; - - // Immediately destroy native side of wrapper, instead of waiting for Java GC. - if (previousEventEmitterWrapper != eventEmitter && previousEventEmitterWrapper != null) { - previousEventEmitterWrapper.destroy(); - } - - Queue pendingEventQueue = viewState.mPendingEventQueue; - if (pendingEventQueue != null) { - // Invoke pending event queued to the view state - for (PendingViewEvent viewEvent : pendingEventQueue) { - viewEvent.dispatch(eventEmitter); - } - viewState.mPendingEventQueue = null; - } - } - - @UiThread - public synchronized void setJSResponder( - int reactTag, int initialReactTag, boolean blockNativeResponder) { - UiThreadUtil.assertOnUiThread(); - if (isStopped()) { - return; - } - - if (!blockNativeResponder) { - mJSResponderHandler.setJSResponder(initialReactTag, null); - return; - } - - ViewState viewState = getViewState(reactTag); - View view = viewState.mView; - if (initialReactTag != reactTag && view instanceof ViewParent) { - // In this case, initialReactTag corresponds to a virtual/layout-only View, and we already - // have a parent of that View in reactTag, so we can use it. - mJSResponderHandler.setJSResponder(initialReactTag, (ViewParent) view); - return; - } else if (view == null) { - SoftAssertions.assertUnreachable("Cannot find view for tag [" + reactTag + "]."); - return; - } - - if (viewState.mIsRoot) { - SoftAssertions.assertUnreachable( - "Cannot block native responder on [" + reactTag + "] that is a root view"); - } - mJSResponderHandler.setJSResponder(initialReactTag, view.getParent()); - } - - @UiThread - private void onViewStateDeleted(ViewState viewState) { - // Destroy state immediately instead of waiting for Java GC. - if (viewState.mStateWrapper != null) { - viewState.mStateWrapper.destroyState(); - viewState.mStateWrapper = null; - } - - // Destroy EventEmitterWrapper immediately instead of waiting for Java GC. - // Notably, this is also required to ensure that the EventEmitterWrapper is deallocated - // before the JS VM is deallocated, since it holds onto a JSI::Pointer. - if (viewState.mEventEmitter != null) { - viewState.mEventEmitter.destroy(); - viewState.mEventEmitter = null; - } - - // For non-root views we notify viewmanager with {@link ViewManager#onDropInstance} - ViewManager viewManager = viewState.mViewManager; - if (!viewState.mIsRoot && viewManager != null) { - viewManager.onDropViewInstance(viewState.mView); - } - } - - @UiThread - public void deleteView(int reactTag) { - UiThreadUtil.assertOnUiThread(); - if (isStopped()) { - return; - } - - if (ReactNativeFeatureFlags.overrideBySynchronousMountPropsAtMountingAndroid() - && mTagToSynchronousMountProps.containsKey(reactTag)) { - mTagToSynchronousMountProps.remove(reactTag); - } - - ViewState viewState = getNullableViewState(reactTag); - - if (viewState == null) { - ReactSoftExceptionLogger.logSoftException( - ReactSoftExceptionLogger.Categories.SURFACE_MOUNTING_MANAGER_MISSING_VIEWSTATE, - new ReactNoCrashSoftException( - "Unable to find viewState for tag: " + reactTag + " for deleteView")); - return; - } - - if (mViewsWithActiveTouches.contains(reactTag)) { - // If the view that went offscreen is still being touched, we can't delete it yet. - // We have to delay the deletion till the touch is completed. - // This is causing bugs like those otherwise: - // - https://github.com/facebook/react-native/issues/44610 - // - https://github.com/facebook/react-native/issues/45126 - mViewsToDeleteAfterTouchFinishes.add(reactTag); - } else { - // To delete we simply remove the tag from the registry. - // We want to rely on the correct set of MountInstructions being sent to the platform, - // or StopSurface being called, so we do not handle deleting descendants of the View. - mTagToViewState.remove(reactTag); - - onViewStateDeleted(viewState); - } - } - - @UiThread - public void preallocateView( - @NonNull String componentName, - int reactTag, - @Nullable ReadableMap props, - @Nullable StateWrapper stateWrapper, - boolean isLayoutable) { - UiThreadUtil.assertOnUiThread(); - - if (isStopped()) { - return; - } - // We treat this as a perf problem and not a logical error. View Preallocation or unexpected - // changes to Differ or C++ Binding could cause some redundant Create instructions. - if (getNullableViewState(reactTag) != null) { - return; - } - - createViewUnsafe(componentName, reactTag, props, stateWrapper, null, isLayoutable); - } - - @AnyThread - @ThreadConfined(ANY) - public @Nullable EventEmitterWrapper getEventEmitter(int reactTag) { - ViewState viewState = getNullableViewState(reactTag); - return viewState == null ? null : viewState.mEventEmitter; - } - - @UiThread - public View getView(int reactTag) { - ViewState state = getNullableViewState(reactTag); - View view = state == null ? null : state.mView; - if (view == null) { - throw new IllegalViewOperationException( - "Trying to resolve view with tag " + reactTag + " which doesn't exist"); - } - return view; - } - - private @NonNull ViewState getViewState(int tag) { - ViewState viewState = mTagToViewState.get(tag); - if (viewState == null) { - throw new RetryableMountingLayerException( - "Unable to find viewState for tag " + tag + ". Surface stopped: " + isStopped()); - } - return viewState; - } - - private @Nullable ViewState getNullableViewState(int tag) { - ConcurrentHashMap viewStates = mTagToViewState; - if (viewStates == null) { - return null; - } - return viewStates.get(tag); - } - - @SuppressWarnings("unchecked") // prevents unchecked conversion warn of the type - private static @NonNull IViewGroupManager getViewGroupManager( - @NonNull ViewState viewState) { - if (viewState.mViewManager == null) { - throw new IllegalStateException("Unable to find ViewManager for view: " + viewState); - } - return (IViewGroupManager) viewState.mViewManager; - } - - public void printSurfaceState() { - FLog.e(TAG, "Views created for surface {%d}:", getSurfaceId()); - for (ViewState viewState : mTagToViewState.values()) { - String viewManagerName = - viewState.mViewManager != null ? viewState.mViewManager.getName() : null; - @Nullable View view = viewState.mView; - @Nullable View parent = view != null ? (View) view.getParent() : null; - @Nullable Integer parentTag = parent != null ? parent.getId() : null; - - FLog.e( - TAG, - "<%s id=%d parentTag=%s isRoot=%b />", - viewManagerName, - viewState.mReactTag, - parentTag, - viewState.mIsRoot); - } - } - - @AnyThread - public void enqueuePendingEvent( - int reactTag, - String eventName, - boolean canCoalesceEvent, - @Nullable WritableMap params, - @EventCategoryDef int eventCategory) { - // When the surface stopped we will reset the view state map. We are not going to enqueue - // pending events as they are not expected to be dispatched anyways. - if (mTagToViewState == null) { - return; - } - - ViewState viewState = mTagToViewState.get(reactTag); - if (viewState == null) { - // Cannot queue event without view state. Do nothing here. - return; - } - - PendingViewEvent viewEvent = - new PendingViewEvent(eventName, params, eventCategory, canCoalesceEvent); - UiThreadUtil.runOnUiThread( - new Runnable() { - @Override - public void run() { - if (viewState.mEventEmitter != null) { - viewEvent.dispatch(viewState.mEventEmitter); - } else { - if (viewState.mPendingEventQueue == null) { - viewState.mPendingEventQueue = new LinkedList<>(); - } - viewState.mPendingEventQueue.add(viewEvent); - } - } - }); - } - - public void markActiveTouchForTag(int reactTag) { - mViewsWithActiveTouches.add(reactTag); - } - - public void sweepActiveTouchForTag(int reactTag) { - mViewsWithActiveTouches.remove(reactTag); - if (mViewsToDeleteAfterTouchFinishes.contains(reactTag)) { - mViewsToDeleteAfterTouchFinishes.remove(reactTag); - deleteView(reactTag); - } - } - - /** - * This class holds view state for react tags. Objects of this class are stored into the {@link - * #mTagToViewState}, and they should be updated in the same thread. - */ - private static class ViewState { - @Nullable View mView = null; - final int mReactTag; - final boolean mIsRoot; - @Nullable ViewManager mViewManager = null; - @Nullable ReactStylesDiffMap mCurrentProps = null; - @Nullable StateWrapper mStateWrapper = null; - @Nullable EventEmitterWrapper mEventEmitter = null; - - @ThreadConfined(UI) - @Nullable - Queue mPendingEventQueue = null; - - private ViewState(int reactTag) { - this(reactTag, null, null, false); - } - - private ViewState( - int reactTag, @Nullable View view, @Nullable ViewManager viewManager, boolean isRoot) { - mReactTag = reactTag; - mView = view; - mIsRoot = isRoot; - mViewManager = viewManager; - } - - @NonNull - @Override - public String toString() { - boolean isLayoutOnly = mViewManager == null; - return "ViewState [" - + mReactTag - + "] - isRoot: " - + mIsRoot - + " - props: " - + mCurrentProps - + " - viewManager: " - + mViewManager - + " - isLayoutOnly: " - + isLayoutOnly; - } - } - - private static class PendingViewEvent { - private final String mEventName; - private final boolean mCanCoalesceEvent; - private final @EventCategoryDef int mEventCategory; - private final @Nullable WritableMap mParams; - - public PendingViewEvent( - String eventName, - @Nullable WritableMap params, - @EventCategoryDef int eventCategory, - boolean canCoalesceEvent) { - mEventName = eventName; - mParams = params; - mEventCategory = eventCategory; - mCanCoalesceEvent = canCoalesceEvent; - } - - public void dispatch(EventEmitterWrapper eventEmitter) { - if (mCanCoalesceEvent) { - eventEmitter.dispatchUnique(mEventName, mParams); - } else { - eventEmitter.dispatch(mEventName, mParams, mEventCategory); - } - } - } -} diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/fabric/mounting/SurfaceMountingManager.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/fabric/mounting/SurfaceMountingManager.kt new file mode 100644 index 00000000000000..a4b463b59d9b2f --- /dev/null +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/fabric/mounting/SurfaceMountingManager.kt @@ -0,0 +1,1257 @@ +/* + * 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. + */ + +package com.facebook.react.fabric.mounting + +import android.annotation.SuppressLint +import android.view.View +import android.view.ViewGroup +import android.view.ViewParent +import androidx.annotation.AnyThread +import androidx.annotation.UiThread +import androidx.collection.SparseArrayCompat +import com.facebook.common.logging.FLog +import com.facebook.infer.annotation.Assertions +import com.facebook.infer.annotation.ThreadConfined +import com.facebook.react.bridge.GuardedRunnable +import com.facebook.react.bridge.ReactNoCrashSoftException +import com.facebook.react.bridge.ReactSoftExceptionLogger +import com.facebook.react.bridge.ReadableArray +import com.facebook.react.bridge.ReadableMap +import com.facebook.react.bridge.ReadableType +import com.facebook.react.bridge.RetryableMountingLayerException +import com.facebook.react.bridge.SoftAssertions +import com.facebook.react.bridge.UiThreadUtil +import com.facebook.react.bridge.WritableMap +import com.facebook.react.bridge.WritableNativeArray +import com.facebook.react.bridge.WritableNativeMap +import com.facebook.react.common.annotations.UnstableReactNativeAPI +import com.facebook.react.common.build.ReactBuildConfig +import com.facebook.react.common.mapbuffer.MapBuffer +import com.facebook.react.fabric.events.EventEmitterWrapper +import com.facebook.react.fabric.mounting.MountingManager.MountItemExecutor +import com.facebook.react.fabric.mounting.mountitems.MountItem +import com.facebook.react.internal.featureflags.ReactNativeFeatureFlags +import com.facebook.react.touch.JSResponderHandler +import com.facebook.react.uimanager.IViewGroupManager +import com.facebook.react.uimanager.IllegalViewOperationException +import com.facebook.react.uimanager.ReactOverflowViewWithInset +import com.facebook.react.uimanager.ReactRoot +import com.facebook.react.uimanager.ReactStylesDiffMap +import com.facebook.react.uimanager.RootView +import com.facebook.react.uimanager.RootViewManager +import com.facebook.react.uimanager.StateWrapper +import com.facebook.react.uimanager.ThemedReactContext +import com.facebook.react.uimanager.ViewManager +import com.facebook.react.uimanager.ViewManagerRegistry +import com.facebook.react.uimanager.events.EventCategoryDef +import com.facebook.systrace.Systrace +import java.util.ArrayDeque +import java.util.LinkedList +import java.util.Queue +import java.util.concurrent.ConcurrentHashMap +import kotlin.concurrent.Volatile + +/** Returns true if the collection contains [key]. */ +private operator fun SparseArrayCompat.contains(key: Int): Boolean = containsKey(key) + +/** Allows the use of the index operator for storing values in the collection. */ +private operator fun SparseArrayCompat.set(key: Int, value: T): Unit = put(key, value) + +public class SurfaceMountingManager +internal constructor( + public val surfaceId: Int, + jsResponderHandler: JSResponderHandler, + viewManagerRegistry: ViewManagerRegistry, + rootViewManager: RootViewManager, + mountItemExecutor: MountItemExecutor, + reactContext: ThemedReactContext, +) { + @Volatile + public var isStopped: Boolean = false + private set + + @Volatile + public var isRootViewAttached: Boolean = false + private set + + public var context: ThemedReactContext? = reactContext + private set + + private val tagToViewState: ConcurrentHashMap = ConcurrentHashMap() // any thread + private val onViewAttachMountItems: Queue = ArrayDeque() + + // These are all non-null, until StopSurface is called + private var jsResponderHandler: JSResponderHandler? = jsResponderHandler + private val viewManagerRegistry: ViewManagerRegistry? = viewManagerRegistry + @Suppress("UNCHECKED_CAST") + private var rootViewManager: ViewManager? = (rootViewManager as ViewManager) + private var mountItemExecutor: MountItemExecutor? = mountItemExecutor + + @ThreadConfined(ThreadConfined.UI) + private val erroneouslyReaddedReactTags: MutableSet = HashSet() + + // This set is used to keep track of views that are currently being interacted with (i.e. + // views that saw a ACTION_DOWN but not a ACTION_UP event yet). This is used to prevent + // views from being removed while they are being interacted with as their event emitter will + // also be removed, and `Pressables` will look "stuck". + @ThreadConfined(ThreadConfined.UI) private val viewsWithActiveTouches: MutableSet = HashSet() + + // This set contains the views that are scheduled to be removed after their touch finishes. + @ThreadConfined(ThreadConfined.UI) + private val viewsToDeleteAfterTouchFinishes: MutableSet = HashSet() + + // This is null *until* StopSurface is called. + private var tagSetForStoppedSurface: SparseArrayCompat? = null + + // This is to make sure direct manipulation result will not be overridden by React update. + @ThreadConfined(ThreadConfined.UI) + private val tagToSynchronousMountProps = SparseArrayCompat>() + + public fun attachRootView(rootView: View, themedReactContext: ThemedReactContext): Unit { + this.context = themedReactContext + addRootView(rootView) + } + + public fun getViewExists(tag: Int): Boolean { + // If Surface stopped, check if tag *was* associated with this Surface, even though it's been + // deleted. This helps distinguish between scenarios where an invalid tag is referenced, vs + // race conditions where an imperative method is called on a tag during/just after StopSurface. + if (tagSetForStoppedSurface?.containsKey(tag) == true) { + return true + } + return tagToViewState.containsKey(tag) + } + + @UiThread + @ThreadConfined(ThreadConfined.UI) + internal fun scheduleMountItemOnViewAttach(item: MountItem): Unit { + onViewAttachMountItems.add(item) + } + + @AnyThread + private fun addRootView(rootView: View) { + if (isStopped) { + return + } + + tagToViewState[surfaceId] = ViewState(surfaceId, rootView, rootViewManager, true) + + val runnable: Runnable = + object : GuardedRunnable(checkNotNull(context)) { + override fun runGuarded() { + // The CPU has ticked since `addRootView` was called, so the surface could technically + // have already stopped here. + if (isStopped) { + return + } + + if (rootView.id == surfaceId) { + ReactSoftExceptionLogger.logSoftException( + TAG, + IllegalViewOperationException( + "Race condition in addRootView detected. Trying to set an id of [$surfaceId] on the RootView, but that id has already been set. " + ), + ) + } else if (rootView.id != View.NO_ID) { + FLog.e( + TAG, + "Trying to add RootTag to RootView that already has a tag: existing tag: [${rootView.id}] new tag: [$surfaceId]", + ) + // This behavior can not be guaranteed in hybrid apps that have a native android layer + // over which reactRootViews are added and the native views need to have ids on them + // in order to work. Hence this can cause unnecessary crashes at runtime for hybrid + // apps. So converting this to a soft exception such that pure react-native devs can + // still see the warning while hybrid apps continue to run without crashes + ReactSoftExceptionLogger.logSoftException( + TAG, + IllegalViewOperationException( + "Trying to add a root view with an explicit id already set. React Native uses the id field to track react tags and will overwrite this field. If that is fine, explicitly overwrite the id field to View.NO_ID before calling addRootView." + ), + ) + } + rootView.id = surfaceId + + if (rootView is ReactRoot) { + rootView.setRootViewTag(surfaceId) + } + + executeMountItemsOnViewAttach() + + // By doing this after `executeMountItemsOnViewAttach`, we ensure that any operations + // scheduled while processing this queue are also added to the queue, instead of being + // processed immediately through the queue in `MountItemDispatcher`. + isRootViewAttached = true + } + } + + if (UiThreadUtil.isOnUiThread()) { + runnable.run() + } else { + UiThreadUtil.runOnUiThread(runnable) + } + } + + @UiThread + @ThreadConfined(ThreadConfined.UI) + private fun executeMountItemsOnViewAttach() { + checkNotNull(mountItemExecutor).executeItems(onViewAttachMountItems) + } + + /** + * Stop surface and all operations within it. Garbage-collect Views (caller is responsible for + * removing RootView from View layer). + * + * Delete rootView from cache. Since RN does not control the RootView, in a sense, the fragment is + * responsible for actually removing the RootView from the hierarchy / tearing down the fragment. + * + * In the original version(s) of this function, we recursively went through all children of the + * View and dropped those Views as well; ad infinitum. This was before we had a + * SurfaceMountingManager, and all tags were in one global map. Doing this was particularly + * important in the case of StopSurface, where race conditions between threads meant you couldn't + * rely on DELETE instructions actually deleting all Views in the Surface. + * + * Now that we have SurfaceMountingManager, we can simply drop our local reference to the View. + * Since it will be removed from the View hierarchy entirely (outside of the scope of this class), + * garbage collection will take care of destroying it and all descendents. + */ + @AnyThread + public fun stopSurface(): Unit { + FLog.e(TAG, "Stopping surface [$surfaceId]") + if (isStopped) { + return + } + + // Prevent more views from being created, or the hierarchy from being manipulated at all. This + // causes further operations to noop. + isStopped = true + + // Reset all StateWrapper objects + // Since this can happen on any thread, is it possible to race between StateWrapper destruction + // and some accesses from View classes in the UI thread? + for (viewState in tagToViewState.values) { + viewState.stateWrapper?.destroyState() + viewState.stateWrapper = null + + viewState.eventEmitter?.destroy() + viewState.eventEmitter = null + } + + val runnable = Runnable { + if (ReactNativeFeatureFlags.enableViewRecycling()) { + viewManagerRegistry?.onSurfaceStopped(surfaceId) + } + val tagSetForStoppedSurface = + SparseArrayCompat().also { this.tagSetForStoppedSurface = it } + for ((key, value) in tagToViewState) { + // Using this as a placeholder value in the map. We're using SparseArrayCompat + // since it can efficiently represent the list of pending tags + tagSetForStoppedSurface[key] = this + + // We must call `onDropViewInstance` on all remaining Views + onViewStateDeleted(value) + } + + // Evict all views from cache and memory + jsResponderHandler = null + rootViewManager = null + mountItemExecutor = null + context = null + tagToViewState.clear() + onViewAttachMountItems.clear() + tagToSynchronousMountProps.clear() + FLog.e(TAG, "Surface [$surfaceId] was stopped on SurfaceMountingManager.") + } + + if (UiThreadUtil.isOnUiThread()) { + runnable.run() + } else { + UiThreadUtil.runOnUiThread(runnable) + } + } + + @UiThread + public fun addViewAt(parentTag: Int, tag: Int, index: Int): Unit { + UiThreadUtil.assertOnUiThread() + if (isStopped) { + return + } + + val parentViewState = getViewState(parentTag) + if (parentViewState.view !is ViewGroup) { + val message = + "Unable to add a view into a view that is not a ViewGroup. ParentTag: $parentTag - Tag: $tag - Index: $index" + FLog.e(TAG, message) + throw IllegalStateException(message) + } + val parentView = parentViewState.view as ViewGroup + val viewState = getViewState(tag) + val view = viewState.view + checkNotNull(view) { "Unable to find view for viewState $viewState and tag $tag" } + + // Display children before inserting + if (SHOW_CHANGED_VIEW_HIERARCHIES) { + FLog.e(TAG, "addViewAt: [$tag] -> [$parentTag] idx: $index BEFORE") + logViewHierarchy(parentView, false) + } + + val viewParent = view.parent + if (viewParent != null) { + val actualParentId = if (viewParent is ViewGroup) viewParent.id else View.NO_ID + ReactSoftExceptionLogger.logSoftException( + TAG, + IllegalStateException( + "addViewAt: cannot insert view [$tag] into parent [$parentTag]: View already has a parent: [$actualParentId] Parent: ${viewParent.javaClass.simpleName} View: ${view.javaClass.simpleName}" + ), + ) + + // We've hit an error case, and `addView` will crash below + // if we don't take evasive action (it is an error to add a View + // to the hierarchy if it already has a parent). + // We don't know /why/ this happens yet, but it does happen + // very infrequently in production. + // Thus, we do three things here: + // (1) We logged a SoftException above, so if there's a crash later + // on, we might have some hints about what caused it. + // (2) We remove the View from its parent. + // (3) In case the View was removed from the hierarchy with the + // RemoveDeleteTree instruction, and is now being readded - which + // should be impossible - we mark this as a "readded" View and + // thus prevent the RemoveDeleteTree worker from deleting this + // View in the future. + if (viewParent is ViewGroup) { + viewParent.removeView(view) + } + erroneouslyReaddedReactTags.add(tag) + } + + try { + getViewGroupManager(parentViewState).addView(parentView, view, index) + } catch (e: IllegalStateException) { + // Wrap error with more context for debugging + throw IllegalStateException( + ("addViewAt: failed to insert view [$tag] into parent [$parentTag] at index $index"), + e, + ) + } catch (e: IndexOutOfBoundsException) { + throw IllegalStateException( + ("addViewAt: failed to insert view [$tag] into parent [$parentTag] at index $index"), + e, + ) + } + + // Display children after inserting + if (SHOW_CHANGED_VIEW_HIERARCHIES) { + // Why are we calling `runOnUiThread`? We're already on the UI thread, right?! + // Yes - but if you get the children of the View here and display them, *it might show you + // the previous children*. Without getting too much into Android internals, basically if we + // wait a tick, everything is what we expect. + // tldr is that `parent.children == []; parent.addView(x); parent.children == []` + // and you need to wait a tick for `parent.children == [x]`. + UiThreadUtil.runOnUiThread { + FLog.e(TAG, "addViewAt: [$tag] -> [$parentTag] idx: $index AFTER") + logViewHierarchy(parentView, false) + } + } + } + + @UiThread + public fun removeViewAt(tag: Int, parentTag: Int, index: Int): Unit { + if (isStopped) { + return + } + + // This is "impossible". See comments above. + if (erroneouslyReaddedReactTags.contains(tag)) { + ReactSoftExceptionLogger.logSoftException( + TAG, + IllegalViewOperationException( + ("removeViewAt tried to remove a React View that was actually reused. This indicates a bug in the Differ (specifically instruction ordering). [$tag]") + ), + ) + return + } + + UiThreadUtil.assertOnUiThread() + val parentViewState = getNullableViewState(parentTag) + + // TODO: throw exception here? + if (parentViewState == null) { + ReactSoftExceptionLogger.logSoftException( + ReactSoftExceptionLogger.Categories.SURFACE_MOUNTING_MANAGER_MISSING_VIEWSTATE, + IllegalStateException("Unable to find viewState for tag: [$parentTag] for removeViewAt"), + ) + return + } + + val parentView = parentViewState.view + if (parentView !is ViewGroup) { + val message = + "Unable to remove a view from a view that is not a ViewGroup. ParentTag: $parentTag - Tag: $tag - Index: $index" + FLog.e(TAG, message) + throw IllegalStateException(message) + } + + if (SHOW_CHANGED_VIEW_HIERARCHIES) { + // Display children before deleting any + FLog.e(TAG, "removeViewAt: [$tag] -> [$parentTag] idx: $index BEFORE") + logViewHierarchy(parentView, false) + } + + val viewGroupManager = getViewGroupManager(parentViewState) + + // Verify that the view we're about to remove has the same tag we expect + val view = viewGroupManager.getChildAt(parentView, index) + val actualTag = view?.id ?: -1 + var actualIndex = index + if (actualTag != tag) { + var tagActualIndex = -1 + val parentChildrenCount = parentView.childCount + for (i in 0.. [$parentTag] @$index: view already removed from parent! Children in parent: ${parentChildrenCount}"), + ) + return + } + + // Here we are guaranteed that the view is still in the View hierarchy, just + // at a different index. In debug mode we'll crash here; in production, we'll remove + // the child from the parent and move on. + // This is an issue that is safely recoverable 95% of the time. If this allows corruption + // of the view hierarchy and causes bugs or a crash after this point, there will be logs + // indicating that this happened. + // This is likely *only* necessary because of Fabric's LayoutAnimations implementation. + // If we can fix the bug there, or remove the need for LayoutAnimation index adjustment + // entirely, we can just throw this exception without regression user experience. + logViewHierarchy(parentView, true) + ReactSoftExceptionLogger.logSoftException( + TAG, + IllegalStateException( + ("Tried to remove view [$tag] of parent [$parentTag] at index $index, but got view tag ${actualTag} - actual index of view: ${tagActualIndex}") + ), + ) + actualIndex = tagActualIndex + } + + try { + viewGroupManager.removeViewAt(parentView, actualIndex) + } catch (e: RuntimeException) { + // Note: `getChildCount` may not always be accurate! + // We don't currently have a good explanation other than, in situations where you + // would empirically expect to see childCount > 0, the childCount is reported as 0. + // This is likely due to a ViewManager overriding getChildCount or some other methods + // in a way that is strictly incorrect, but potentially only visible here. + // The failure mode is actually that in `removeViewAt`, a NullPointerException is + // thrown when we try to perform an operation on a View that doesn't exist, and + // is therefore null. + // We try to add some extra diagnostics here, but we always try to remove the View + // from the hierarchy first because detecting by looking at childCount will not work. + // + // Note that the lesson here is that `getChildCount` is not /required/ to adhere to + // any invariants. If you add 9 children to a parent, the `getChildCount` of the parent + // may not be equal to 9. This apparently causes no issues with Android and is common + // enough that we shouldn't try to change this invariant, without a lot of thought. + val childCount = viewGroupManager.getChildCount(parentView) + + logViewHierarchy(parentView, true) + + throw IllegalStateException( + "Cannot remove child at index ${actualIndex} from parent ViewGroup [${parentView.id}], only ${childCount} children in parent. Warning: childCount may be incorrect!", + e, + ) + } + + // Display children after deleting any + if (SHOW_CHANGED_VIEW_HIERARCHIES) { + UiThreadUtil.runOnUiThread { + FLog.e(TAG, ("removeViewAt: [$tag] -> [$parentTag] idx: ${actualIndex} AFTER")) + logViewHierarchy(parentView, false) + } + } + } + + @UiThread + internal fun createView( + componentName: String, + reactTag: Int, + props: ReadableMap, + stateWrapper: StateWrapper?, + eventEmitterWrapper: EventEmitterWrapper?, + isLayoutable: Boolean, + ): Unit { + if (isStopped) { + return + } + // We treat this as a perf problem and not a logical error. View Preallocation or unexpected + // changes to Differ or C++ Binding could cause some redundant Create instructions. + // There are cases where preallocation happens and a node is recreated: if a node is + // preallocated and then committed with revision 2+, an extra CREATE instruction will be + // generated. + // This represents a perf issue only, not a correctness issue. In the future we need to + // refactor View preallocation to correct the currently incorrect assumptions. + val viewState = getNullableViewState(reactTag) + if (viewState?.view != null) { + return + } + + createViewUnsafe( + componentName, + reactTag, + props, + stateWrapper, + eventEmitterWrapper, + isLayoutable, + ) + } + + /** + * Perform view creation without any safety checks. You must ensure safety before calling this + * method (see existing callsites). + * + * @param componentName + * @param reactTag + * @param props + * @param stateWrapper + * @param eventEmitterWrapper + * @param isLayoutable + */ + @UiThread + private fun createViewUnsafe( + componentName: String, + reactTag: Int, + props: ReadableMap, + stateWrapper: StateWrapper?, + eventEmitterWrapper: EventEmitterWrapper?, + isLayoutable: Boolean, + ): Unit { + Systrace.beginSection( + Systrace.TRACE_TAG_REACT, + "SurfaceMountingManager::createViewUnsafe($componentName)", + ) + try { + val propMap = ReactStylesDiffMap(props) + val viewState = + ViewState(reactTag).apply { + this.currentProps = propMap + this.stateWrapper = stateWrapper + this.eventEmitter = eventEmitterWrapper + } + tagToViewState[reactTag] = viewState + + if (isLayoutable) { + @Suppress("UNCHECKED_CAST") + val viewManager = viewManagerRegistry?.get(componentName) as ViewManager + // View Managers are responsible for dealing with inital state and props. + viewState.view = + viewManager.createView(reactTag, context!!, propMap, stateWrapper, jsResponderHandler) + viewState.viewManager = viewManager + } + } finally { + Systrace.endSection(Systrace.TRACE_TAG_REACT) + } + } + + public fun storeSynchronousMountPropsOverride(reactTag: Int, props: ReadableMap): Unit { + if (ReactNativeFeatureFlags.overrideBySynchronousMountPropsAtMountingAndroid()) { + val propsMap = getMapFromPropsReadableMap(props) + if (reactTag in tagToSynchronousMountProps) { + val mergedPropsMap = checkNotNull(tagToSynchronousMountProps[reactTag]) + mergedPropsMap.putAll(propsMap) + tagToSynchronousMountProps[reactTag] = mergedPropsMap + } else { + tagToSynchronousMountProps[reactTag] = propsMap + } + } + } + + public fun updatePropsSynchronously(reactTag: Int, props: ReadableMap): Unit { + updateProps(reactTag, props, true) + } + + public fun updateProps(reactTag: Int, props: ReadableMap): Unit { + updateProps(reactTag, props, false) + } + + @UiThread + private fun updateProps( + reactTag: Int, + props: ReadableMap, + shouldSkipSynchronousMountPropsOverride: Boolean, + ) { + if (isStopped) { + return + } + + val viewState = getViewState(reactTag) + + if ( + ReactNativeFeatureFlags.overrideBySynchronousMountPropsAtMountingAndroid() && + !shouldSkipSynchronousMountPropsOverride && + tagToSynchronousMountProps.containsKey(reactTag) + ) { + val modifiedProps = WritableNativeMap() + modifiedProps.merge(props) + val directPropsMap = + Assertions.assertNotNull>(tagToSynchronousMountProps[reactTag]) + overridePropsReadableMap(directPropsMap, modifiedProps) + viewState.currentProps = ReactStylesDiffMap(modifiedProps) + } else { + viewState.currentProps = ReactStylesDiffMap(props) + } + + val view: View = checkNotNull(viewState.view) { "Unable to find view for tag [$reactTag]" } + checkNotNull(viewState.viewManager).updateProperties(view, viewState.currentProps) + } + + /** + * This prefetch method is experimental, do not use it for production code. it will most likely + * change or be removed in the future. + * + * @param surfaceId surface ID + * @param componentName + * @param params prefetch request params defined in C++ + */ + @SuppressLint("FunctionName") + @AnyThread + @UnstableReactNativeAPI + public fun experimental_prefetchResources( + surfaceId: Int, + componentName: String, + params: MapBuffer?, + ): Unit { + if (isStopped) { + return + } + viewManagerRegistry + ?.get(componentName) + ?.experimental_prefetchResources(surfaceId, checkNotNull(context), params) + } + + @Deprecated("") + public fun receiveCommand(reactTag: Int, commandId: Int, commandArgs: ReadableArray?): Unit { + if (isStopped) { + return + } + + val viewState = + getNullableViewState(reactTag) + ?: throw RetryableMountingLayerException( + "Unable to find viewState for tag: [$reactTag] for commandId: $commandId" + ) + + // It's not uncommon for JS to send events as/after a component is being removed from the + // view hierarchy. For example, TextInput may send a "blur" command in response to the view + // disappearing. Throw `ReactNoCrashSoftException` so they're logged but don't crash in dev + // for now. + + val viewManager = viewState.viewManager + if (viewManager == null) { + throw RetryableMountingLayerException("Unable to find viewManager for tag $reactTag") + } + + val view = viewState.view + if (view == null) { + throw RetryableMountingLayerException("Unable to find viewState view for tag $reactTag") + } + + @Suppress("DEPRECATION") viewManager.receiveCommand(view, commandId, commandArgs) + } + + public fun receiveCommand(reactTag: Int, commandId: String, commandArgs: ReadableArray?): Unit { + if (isStopped) { + return + } + + val viewState = + getNullableViewState(reactTag) + ?: throw RetryableMountingLayerException( + "Unable to find viewState for tag: $reactTag for commandId: $commandId" + ) + + // It's not uncommon for JS to send events as/after a component is being removed from the + // view hierarchy. For example, TextInput may send a "blur" command in response to the view + // disappearing. Throw `ReactNoCrashSoftException` so they're logged but don't crash in dev + // for now. + + val viewManager = viewState.viewManager + if (viewManager == null) { + throw RetryableMountingLayerException("Unable to find viewState manager for tag $reactTag") + } + + val view = viewState.view + if (view == null) { + throw RetryableMountingLayerException("Unable to find viewState view for tag $reactTag") + } + + viewManager.receiveCommand(view, commandId, commandArgs) + } + + public fun sendAccessibilityEvent(reactTag: Int, eventType: Int): Unit { + if (isStopped) { + return + } + + val view = getViewState(reactTag).view + if (view == null) { + throw RetryableMountingLayerException("Unable to find viewState view for tag $reactTag") + } + + view.sendAccessibilityEvent(eventType) + } + + @UiThread + public fun updateLayout( + reactTag: Int, + parentTag: Int, + x: Int, + y: Int, + width: Int, + height: Int, + displayType: Int, + layoutDirection: Int, + ): Unit { + if (isStopped) { + return + } + + val viewState = getViewState(reactTag) + // Do not layout Root Views + if (viewState.isRoot) { + return + } + + val viewToUpdate = checkNotNull(viewState.view) { "Unable to find View for tag: $reactTag" } + + viewToUpdate.layoutDirection = + when (layoutDirection) { + 1 -> View.LAYOUT_DIRECTION_LTR + 2 -> View.LAYOUT_DIRECTION_RTL + else -> View.LAYOUT_DIRECTION_INHERIT + } + + // Even though we have exact dimensions, we still call measure because some platform views (e.g. + // Switch) assume that method will always be called before onLayout and onDraw. They use it to + // calculate and cache information used in the draw pass. For most views, onMeasure can be + // stubbed out to only call setMeasuredDimensions. For ViewGroups, onLayout should be stubbed + // out to not recursively call layout on its children: React Native already handles doing + // that. + // + // Also, note measure and layout need to be called *after* all View properties have been updated + // because of caching and calculation that may occur in onMeasure and onLayout. Layout + // operations should also follow the native view hierarchy and go top to bottom for + // consistency with standard layout passes (some views may depend on this). + viewToUpdate.measure( + View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.EXACTLY), + View.MeasureSpec.makeMeasureSpec(height, View.MeasureSpec.EXACTLY), + ) + + // We update the layout of the RootView when there is a change in the layout of its child. This + // is required to re-measure the size of the native View container (usually a FrameLayout) that + // is configured with layout_height = WRAP_CONTENT or layout_width = WRAP_CONTENT + // + // This code is going to be executed ONLY when there is a change in the size of the root view + // defined in the JS side. Changes in the layout of inner views will not trigger an update on + // the layout of the root view. + val parent = viewToUpdate.parent + if (parent is RootView) { + parent.requestLayout() + } + + // TODO T212247085: Make this non-nullable again after rolling out + // disableMountItemReorderingAndroid + val parentViewState = getNullableViewState(parentTag) + var parentViewManager: IViewGroupManager<*>? = null + if (parentViewState == null) { + ReactSoftExceptionLogger.logSoftException( + ReactSoftExceptionLogger.Categories.SURFACE_MOUNTING_MANAGER_MISSING_VIEWSTATE, + ReactNoCrashSoftException( + "Unable to find viewState for tag: $parentTag for updateLayout" + ), + ) + } else if (parentViewState.viewManager != null) { + parentViewManager = parentViewState.viewManager as IViewGroupManager<*> + } + if (parentViewManager == null || !parentViewManager.needsCustomLayoutForChildren()) { + viewToUpdate.layout(x, y, x + width, y + height) + } + + // displayType: 0 represents display: 'none' + val visibility = if (displayType == 0) View.INVISIBLE else View.VISIBLE + if (viewToUpdate.visibility != visibility) { + viewToUpdate.visibility = visibility + } + } + + @UiThread + public fun updatePadding(reactTag: Int, left: Int, top: Int, right: Int, bottom: Int): Unit { + UiThreadUtil.assertOnUiThread() + if (isStopped) { + return + } + + val viewState = getViewState(reactTag) + // Do not layout Root Views + if (viewState.isRoot) { + return + } + + val viewToUpdate = checkNotNull(viewState.view) { "Unable to find View for tag: $reactTag" } + val viewManager = + checkNotNull(viewState.viewManager) { "Unable to find ViewManager for view: $viewState" } + + // noinspection unchecked + viewManager.setPadding(viewToUpdate, left, top, right, bottom) + } + + @UiThread + public fun updateOverflowInset( + reactTag: Int, + overflowInsetLeft: Int, + overflowInsetTop: Int, + overflowInsetRight: Int, + overflowInsetBottom: Int, + ): Unit { + if (isStopped) { + return + } + + val viewState = getViewState(reactTag) + // Do not layout Root Views + if (viewState.isRoot) { + return + } + + val viewToUpdate = viewState.view + checkNotNull(viewToUpdate) { "Unable to find View for tag: $reactTag" } + + if (viewToUpdate is ReactOverflowViewWithInset) { + (viewToUpdate as ReactOverflowViewWithInset).setOverflowInset( + overflowInsetLeft, + overflowInsetTop, + overflowInsetRight, + overflowInsetBottom, + ) + } + } + + @UiThread + public fun updateState(reactTag: Int, stateWrapper: StateWrapper?): Unit { + UiThreadUtil.assertOnUiThread() + if (isStopped) { + return + } + + val viewState = getViewState(reactTag) + + val prevStateWrapper = viewState.stateWrapper + viewState.stateWrapper = stateWrapper + + val viewManager = + checkNotNull(viewState.viewManager) { "Unable to find ViewManager for tag: $reactTag" } + val view = checkNotNull(viewState.view) + + val extraData = viewManager.updateState(view, viewState.currentProps, stateWrapper) + if (extraData != null) { + viewManager.updateExtraData(view, extraData) + } + + // Immediately clear native side of previous state wrapper. This causes the State object in C++ + // to be destroyed immediately instead of waiting for Java GC to kick in. + prevStateWrapper?.destroyState() + } + + /** We update the event emitter from the main thread when the view is mounted. */ + @UiThread + internal fun updateEventEmitter(reactTag: Int, eventEmitter: EventEmitterWrapper): Unit { + UiThreadUtil.assertOnUiThread() + if (isStopped) { + return + } + + var viewState = tagToViewState[reactTag] + if (viewState == null) { + // TODO T62717437 - Use a flag to determine that these event emitters belong to virtual nodes + // only. + viewState = ViewState(reactTag) + tagToViewState[reactTag] = viewState + } + val previousEventEmitterWrapper = viewState.eventEmitter + viewState.eventEmitter = eventEmitter + + // Immediately destroy native side of wrapper, instead of waiting for Java GC. + if (previousEventEmitterWrapper != eventEmitter && previousEventEmitterWrapper != null) { + previousEventEmitterWrapper.destroy() + } + + val pendingEventQueue = viewState.pendingEventQueue + if (pendingEventQueue != null) { + // Invoke pending event queued to the view state + for (viewEvent in pendingEventQueue) { + viewEvent.dispatch(eventEmitter) + } + viewState.pendingEventQueue = null + } + } + + @UiThread + @Synchronized + public fun setJSResponder( + reactTag: Int, + initialReactTag: Int, + blockNativeResponder: Boolean, + ): Unit { + UiThreadUtil.assertOnUiThread() + if (isStopped) { + return + } + + val jsResponderHandler = jsResponderHandler ?: return + + if (!blockNativeResponder) { + jsResponderHandler.setJSResponder(initialReactTag, null) + return + } + + val viewState = getViewState(reactTag) + val view = viewState.view + if (initialReactTag != reactTag && view is ViewParent) { + // In this case, initialReactTag corresponds to a virtual/layout-only View, and we already + // have a parent of that View in reactTag, so we can use it. + jsResponderHandler.setJSResponder(initialReactTag, view as ViewParent) + return + } else if (view == null) { + SoftAssertions.assertUnreachable("Cannot find view for tag [$reactTag].") + return + } + + if (viewState.isRoot) { + SoftAssertions.assertUnreachable( + "Cannot block native responder on [$reactTag] that is a root view" + ) + } + jsResponderHandler.setJSResponder(initialReactTag, view.parent) + } + + @UiThread + private fun onViewStateDeleted(viewState: ViewState) { + // Destroy state immediately instead of waiting for Java GC. + viewState.stateWrapper?.destroyState() + viewState.stateWrapper = null + + // Destroy EventEmitterWrapper immediately instead of waiting for Java GC. + // Notably, this is also required to ensure that the EventEmitterWrapper is deallocated + // before the JS VM is deallocated, since it holds onto a JSI::Pointer. + viewState.eventEmitter?.destroy() + viewState.eventEmitter = null + + // For non-root views we notify viewmanager with [ViewManager#onDropInstance] + val viewManager = viewState.viewManager + if (!viewState.isRoot && viewManager != null) { + viewManager.onDropViewInstance(viewState.view!!) + } + } + + @UiThread + public fun deleteView(reactTag: Int): Unit { + UiThreadUtil.assertOnUiThread() + if (isStopped) { + return + } + + if ( + ReactNativeFeatureFlags.overrideBySynchronousMountPropsAtMountingAndroid() && + tagToSynchronousMountProps.containsKey(reactTag) + ) { + tagToSynchronousMountProps.remove(reactTag) + } + + val viewState = getNullableViewState(reactTag) + + if (viewState == null) { + ReactSoftExceptionLogger.logSoftException( + ReactSoftExceptionLogger.Categories.SURFACE_MOUNTING_MANAGER_MISSING_VIEWSTATE, + ReactNoCrashSoftException("Unable to find viewState for tag: $reactTag for deleteView"), + ) + return + } + + if (viewsWithActiveTouches.contains(reactTag)) { + // If the view that went offscreen is still being touched, we can't delete it yet. + // We have to delay the deletion till the touch is completed. + // This is causing bugs like those otherwise: + // - https://github.com/facebook/react-native/issues/44610 + // - https://github.com/facebook/react-native/issues/45126 + viewsToDeleteAfterTouchFinishes.add(reactTag) + } else { + // To delete we simply remove the tag from the registry. + // We want to rely on the correct set of MountInstructions being sent to the platform, + // or StopSurface being called, so we do not handle deleting descendants of the View. + tagToViewState.remove(reactTag) + + onViewStateDeleted(viewState) + } + } + + @UiThread + public fun preallocateView( + componentName: String, + reactTag: Int, + props: ReadableMap, + stateWrapper: StateWrapper?, + isLayoutable: Boolean, + ): Unit { + UiThreadUtil.assertOnUiThread() + + if (isStopped) { + return + } + // We treat this as a perf problem and not a logical error. View Preallocation or unexpected + // changes to Differ or C++ Binding could cause some redundant Create instructions. + if (getNullableViewState(reactTag) != null) { + return + } + + createViewUnsafe(componentName, reactTag, props, stateWrapper, null, isLayoutable) + } + + @AnyThread + @ThreadConfined(ThreadConfined.ANY) + internal fun getEventEmitter(reactTag: Int): EventEmitterWrapper? { + val viewState = getNullableViewState(reactTag) + return viewState?.eventEmitter + } + + @UiThread + public fun getView(reactTag: Int): View { + val state = getNullableViewState(reactTag) + val view = + state?.view + ?: throw IllegalViewOperationException( + "Trying to resolve view with tag $reactTag which doesn't exist" + ) + return view + } + + private fun getViewState(tag: Int): ViewState = + tagToViewState[tag] + ?: throw RetryableMountingLayerException( + "Unable to find viewState for tag $tag. Surface stopped: $isStopped" + ) + + private fun getNullableViewState(tag: Int): ViewState? = tagToViewState[tag] + + public fun printSurfaceState(): Unit { + FLog.e(TAG, "Views created for surface $surfaceId:") + for (viewState in tagToViewState.values) { + val viewManagerName = viewState.viewManager?.name + val view = viewState.view + val parent = if (view != null) view.parent as View? else null + val parentTag = parent?.id + + FLog.e( + TAG, + "<$viewManagerName id=${viewState.reactTag} parentTag=$parentTag isRoot=${viewState.isRoot} />", + ) + } + } + + @AnyThread + public fun enqueuePendingEvent( + reactTag: Int, + eventName: String, + canCoalesceEvent: Boolean, + params: WritableMap?, + @EventCategoryDef eventCategory: Int, + ): Unit { + // When the surface stopped we will reset the view state map. We are not going to enqueue + // pending events as they are not expected to be dispatched anyways. + val viewState = tagToViewState[reactTag] + + if (viewState == null) { + // Cannot queue event without view state. Do nothing here. + return + } + + val viewEvent = PendingViewEvent(eventName, params, eventCategory, canCoalesceEvent) + UiThreadUtil.runOnUiThread { + val eventEmitter = viewState.eventEmitter + if (eventEmitter != null) { + viewEvent.dispatch(eventEmitter) + } else { + val queue = + viewState.pendingEventQueue + ?: LinkedList().also { viewState.pendingEventQueue = it } + queue.add(viewEvent) + } + } + } + + public fun markActiveTouchForTag(reactTag: Int): Unit { + viewsWithActiveTouches.add(reactTag) + } + + public fun sweepActiveTouchForTag(reactTag: Int): Unit { + viewsWithActiveTouches.remove(reactTag) + if (viewsToDeleteAfterTouchFinishes.contains(reactTag)) { + viewsToDeleteAfterTouchFinishes.remove(reactTag) + deleteView(reactTag) + } + } + + /** + * This class holds view state for react tags. Objects of this class are stored into the + * [mTagToViewState], and they should be updated in the same thread. + */ + private class ViewState( + val reactTag: Int, + var view: View? = null, + var viewManager: ViewManager? = null, + val isRoot: Boolean = false, + ) { + var currentProps: ReactStylesDiffMap? = null + var stateWrapper: StateWrapper? = null + var eventEmitter: EventEmitterWrapper? = null + + @ThreadConfined(ThreadConfined.UI) var pendingEventQueue: Queue? = null + + override fun toString(): String { + val isLayoutOnly = viewManager == null + return "ViewState [$reactTag] - isRoot: $isRoot - props: $currentProps - viewManager: $viewManager - isLayoutOnly: $isLayoutOnly" + } + } + + private class PendingViewEvent( + private val eventName: String, + private val params: WritableMap?, + @field:EventCategoryDef private val eventCategory: Int, + private val canCoalesceEvent: Boolean, + ) { + fun dispatch(eventEmitter: EventEmitterWrapper) { + if (canCoalesceEvent) { + eventEmitter.dispatchUnique(eventName, params) + } else { + eventEmitter.dispatch(eventName, params, eventCategory) + } + } + } + + public companion object { + @get:JvmStatic public val TAG: String = SurfaceMountingManager::class.java.simpleName + + private val SHOW_CHANGED_VIEW_HIERARCHIES = ReactBuildConfig.DEBUG && false + private const val PROP_TRANSFORM = "transform" + private const val PROP_OPACITY = "opacity" + + private fun logViewHierarchy(parent: ViewGroup, recurse: Boolean) { + val parentTag = parent.id + FLog.e(TAG, " ") + for (i in 0.."), + ) + } + FLog.e(TAG, " ") + + if (recurse) { + FLog.e(TAG, "Displaying Ancestors:") + var ancestor = parent.parent + while (ancestor != null) { + val ancestorViewGroup = if (ancestor is ViewGroup) ancestor else null + val ancestorId = ancestorViewGroup?.id ?: View.NO_ID + FLog.e(TAG, "") + ancestor = ancestor.parent + } + } + } + + private fun overridePropsReadableMap( + patchMap: Map, + outputReadableMap: WritableMap, + ) { + for ((propKey, propValue) in patchMap) { + if (outputReadableMap.hasKey(propKey)) { + if (propKey == PROP_TRANSFORM) { + assert(outputReadableMap.getType(propKey) == ReadableType.Array && propValue is List<*>) + val array = WritableNativeArray() + for (item in propValue as List<*>) { + if (item is Map<*, *>) { + val itemMap = WritableNativeMap() + @Suppress("UNCHECKED_CAST") + for ((key, value) in (item as Map)) { + if (value is String) { + itemMap.putString(key, value) + } else if (value is Number) { + itemMap.putDouble(key, value.toDouble()) + } + } + array.pushMap(itemMap) + } + } + outputReadableMap.putArray(propKey, array) + } else if (propKey == PROP_OPACITY) { + assert(outputReadableMap.getType(propKey) == ReadableType.Number && propValue is Number) + outputReadableMap.putDouble(propKey, (propValue as Number).toDouble()) + } + } + } + } + + private fun getMapFromPropsReadableMap(readableMap: ReadableMap): MutableMap { + val outputMap = mutableMapOf() + + if ( + readableMap.hasKey(PROP_TRANSFORM) && + readableMap.getType(PROP_TRANSFORM) == ReadableType.Array + ) { + val transformArray = readableMap.getArray(PROP_TRANSFORM) + if (transformArray != null) { + val arrayList = ArrayList>(transformArray.size()) + for (i in 0.. type + private fun getViewGroupManager(viewState: ViewState): IViewGroupManager { + val viewManager = + checkNotNull(viewState.viewManager) { "Unable to find ViewManager for view: $viewState" } + @Suppress("UNCHECKED_CAST") + return viewManager as IViewGroupManager + } + } +} diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/fabric/mounting/mountitems/IntBufferBatchMountItem.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/fabric/mounting/mountitems/IntBufferBatchMountItem.kt index 221171fb470398..086eb37e68685d 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/fabric/mounting/mountitems/IntBufferBatchMountItem.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/fabric/mounting/mountitems/IntBufferBatchMountItem.kt @@ -109,7 +109,7 @@ internal class IntBufferBatchMountItem( surfaceMountingManager.createView( fabricComponentName, intBuffer[i++], - objBuffer[j++] as ReadableMap?, + objBuffer[j++] as ReadableMap, objBuffer[j++] as StateWrapper?, objBuffer[j++] as EventEmitterWrapper?, intBuffer[i++] == 1, @@ -124,7 +124,7 @@ internal class IntBufferBatchMountItem( INSTRUCTION_REMOVE -> surfaceMountingManager.removeViewAt(intBuffer[i++], intBuffer[i++], intBuffer[i++]) INSTRUCTION_UPDATE_PROPS -> - surfaceMountingManager.updateProps(intBuffer[i++], objBuffer[j++] as ReadableMap?) + surfaceMountingManager.updateProps(intBuffer[i++], objBuffer[j++] as ReadableMap) INSTRUCTION_UPDATE_STATE -> surfaceMountingManager.updateState(intBuffer[i++], objBuffer[j++] as StateWrapper?) INSTRUCTION_UPDATE_LAYOUT -> { diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/fabric/mounting/mountitems/MountItemFactory.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/fabric/mounting/mountitems/MountItemFactory.kt index 677a5696e0a9ab..006a075c07ca19 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/fabric/mounting/mountitems/MountItemFactory.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/fabric/mounting/mountitems/MountItemFactory.kt @@ -47,7 +47,7 @@ internal object MountItemFactory { surfaceId: Int, reactTag: Int, component: String, - props: ReadableMap?, + props: ReadableMap, stateWrapper: StateWrapper?, isLayoutable: Boolean, ): MountItem = diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/fabric/mounting/mountitems/PreAllocateViewMountItem.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/fabric/mounting/mountitems/PreAllocateViewMountItem.kt index b20662fe585785..72af0e279d62f1 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/fabric/mounting/mountitems/PreAllocateViewMountItem.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/fabric/mounting/mountitems/PreAllocateViewMountItem.kt @@ -19,7 +19,7 @@ internal class PreAllocateViewMountItem( private val surfaceId: Int, private val reactTag: Int, component: String, - private val props: ReadableMap?, + private val props: ReadableMap, private val stateWrapper: StateWrapper?, private val isLayoutable: Boolean, ) : MountItem {