Migrate UIManagerModule from Java to Kotlin (#56996)

Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/56996

Migrate `UIManagerModule` from Java to Kotlin as part of the ongoing Kotlin migration effort. This is a mechanical conversion of a deprecated legacy module with no functional changes.

Changelog:
[Android][Changed] - Migrate `UIManagerModule` from Java to Kotlin

Reviewed By: javache

Differential Revision: D106080563

fbshipit-source-id: 2d0b21cc26c50e1e026b579e4adcee7e71a2be18
This commit is contained in:
Nicola Corti authored and meta-codesync[bot] committed 2026-06-01 17:04:17 -07:00
1 parent d659203db2
commit 21dfc2a855
4 files changed
+695 -697

No files matched your search

@@ -4227,6 +4227,7 @@ public final class com/facebook/react/uimanager/UIManagerHelper {
}
public class com/facebook/react/uimanager/UIManagerModule : com/facebook/react/bridge/ReactContextBaseJavaModule, com/facebook/react/bridge/LifecycleEventListener, com/facebook/react/bridge/UIManager {
public static final field Companion Lcom/facebook/react/uimanager/UIManagerModule$Companion;
public static final field NAME Ljava/lang/String;
public static final field TAG Ljava/lang/String;
public fun <init> (Lcom/facebook/react/bridge/ReactApplicationContext;Lcom/facebook/react/uimanager/ViewManagerResolver;I)V
@@ -4237,14 +4238,14 @@ public class com/facebook/react/uimanager/UIManagerModule : com/facebook/react/b
public fun addUIManagerEventListener (Lcom/facebook/react/bridge/UIManagerListener;)V
public fun clearJSResponder ()V
public fun configureNextLayoutAnimation (Lcom/facebook/react/bridge/ReadableMap;Lcom/facebook/react/bridge/Callback;Lcom/facebook/react/bridge/Callback;)V
public static fun createConstants (Ljava/util/List;Ljava/util/Map;Ljava/util/Map;)Ljava/util/Map;
public static final fun createConstants (Ljava/util/List;Ljava/util/Map;Ljava/util/Map;)Ljava/util/Map;
public fun createView (ILjava/lang/String;ILcom/facebook/react/bridge/ReadableMap;)V
public fun dispatchCommand (IILcom/facebook/react/bridge/ReadableArray;)V
public fun dispatchCommand (ILjava/lang/String;Lcom/facebook/react/bridge/ReadableArray;)V
public fun dispatchViewManagerCommand (ILcom/facebook/react/bridge/Dynamic;Lcom/facebook/react/bridge/ReadableArray;)V
public fun findSubviewIn (ILcom/facebook/react/bridge/ReadableArray;Lcom/facebook/react/bridge/Callback;)V
public fun getConstants ()Ljava/util/Map;
public static fun getConstantsForViewManager (Lcom/facebook/react/uimanager/ViewManager;Ljava/util/Map;)Lcom/facebook/react/bridge/WritableMap;
public static final fun getConstantsForViewManager (Lcom/facebook/react/uimanager/ViewManager;Ljava/util/Map;)Lcom/facebook/react/bridge/WritableMap;
public fun getConstantsForViewManager (Ljava/lang/String;)Lcom/facebook/react/bridge/WritableMap;
public fun getDefaultEventTypes ()Lcom/facebook/react/bridge/WritableMap;
public fun getDirectEventNamesResolver ()Lcom/facebook/react/uimanager/UIManagerModule$CustomEventNamesResolver;
@@ -4288,6 +4289,11 @@ public class com/facebook/react/uimanager/UIManagerModule : com/facebook/react/b
public fun viewIsDescendantOf (IILcom/facebook/react/bridge/Callback;)V
}
public final class com/facebook/react/uimanager/UIManagerModule$Companion {
public final fun createConstants (Ljava/util/List;Ljava/util/Map;Ljava/util/Map;)Ljava/util/Map;
public final fun getConstantsForViewManager (Lcom/facebook/react/uimanager/ViewManager;Ljava/util/Map;)Lcom/facebook/react/bridge/WritableMap;
}
public abstract interface class com/facebook/react/uimanager/UIManagerModule$CustomEventNamesResolver {
public abstract fun resolveCustomEventName (Ljava/lang/String;)Ljava/lang/String;
}
@@ -1,659 +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.uimanager;
import static com.facebook.react.bridge.ReactMarkerConstants.CREATE_UI_MANAGER_MODULE_CONSTANTS_END;
import static com.facebook.react.bridge.ReactMarkerConstants.CREATE_UI_MANAGER_MODULE_CONSTANTS_START;
import static com.facebook.react.uimanager.common.UIManagerType.FABRIC;
import android.content.ComponentCallbacks2;
import android.content.res.Configuration;
import android.view.View;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.facebook.common.logging.FLog;
import com.facebook.debug.holder.PrinterHolder;
import com.facebook.debug.tags.ReactDebugOverlayTags;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.Callback;
import com.facebook.react.bridge.Dynamic;
import com.facebook.react.bridge.LifecycleEventListener;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMarker;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.ReadableArray;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.bridge.ReadableType;
import com.facebook.react.bridge.UIManager;
import com.facebook.react.bridge.UIManagerListener;
import com.facebook.react.bridge.UiThreadUtil;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.common.MapBuilder;
import com.facebook.react.common.ReactConstants;
import com.facebook.react.common.annotations.internal.LegacyArchitecture;
import com.facebook.react.common.annotations.internal.LegacyArchitectureLogLevel;
import com.facebook.react.common.annotations.internal.LegacyArchitectureLogger;
import com.facebook.react.common.build.ReactBuildConfig;
import com.facebook.react.module.annotations.ReactModule;
import com.facebook.react.uimanager.common.ViewUtil;
import com.facebook.react.uimanager.events.EventDispatcher;
import com.facebook.react.uimanager.internal.LegacyArchitectureShadowNodeLogger;
import com.facebook.systrace.Systrace;
import com.facebook.systrace.SystraceMessage;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;
/**
* Native module to allow JS to create and update native Views.
*
* <p>
*
* <h2>== Transactional Requirement ==</h2>
*
* A requirement of this class is to make sure that transactional UI updates occur all at once,
* meaning that no intermediate state is ever rendered to the screen. For example, if a JS
* application update changes the background of View A to blue and the width of View B to 100, both
* need to appear at once. Practically, this means that all UI update code related to a single
* transaction must be executed as a single code block on the UI thread. Executing as multiple code
* blocks could allow the platform UI system to interrupt and render a partial UI state.
*
* <p>To facilitate this, this module enqueues operations that are then applied to native view
* hierarchy at the end of each transaction.
*
* <p>
*
* <h2>== CSSNodes ==</h2>
*
* In order to allow layout and measurement to occur on a non-UI thread, this module also operates
* on intermediate CSSNodeDEPRECATED objects that correspond to a native view. These
* CSSNodeDEPRECATED are able to calculate layout according to their styling rules, and then the
* resulting x/y/width/height of that layout is scheduled as an operation that will be applied to
* native view hierarchy at the end of current batch. TODO(5241856): Investigate memory usage of
* creating many small objects in UIManageModule and consider implementing a pool TODO(5483063):
* Don't dispatch the view hierarchy at the end of a batch if no UI changes occurred
*/
@ReactModule(name = UIManagerModule.NAME)
@LegacyArchitecture(logLevel = LegacyArchitectureLogLevel.ERROR)
@Deprecated(
since = "This class is part of Legacy Architecture and will be removed in a future release")
public class UIManagerModule extends ReactContextBaseJavaModule
implements LifecycleEventListener, UIManager {
static {
LegacyArchitectureLogger.assertLegacyArchitecture(
"UIManagerModule", LegacyArchitectureLogLevel.ERROR);
}
public static final String TAG = UIManagerModule.class.getSimpleName();
/** Resolves a name coming from native side to a name of the event that is exposed to JS. */
public interface CustomEventNamesResolver {
/** Returns custom event name by the provided event name. */
@Nullable
String resolveCustomEventName(String eventName);
}
public static final String NAME = "UIManager";
private static final boolean DEBUG =
PrinterHolder.getPrinter().shouldDisplayLogMessage(ReactDebugOverlayTags.UI_MANAGER);
private final Map<String, Object> mModuleConstants;
private final Map<String, Object> mCustomDirectEvents;
private final ViewManagerRegistry mViewManagerRegistry;
private final MemoryTrimCallback mMemoryTrimCallback = new MemoryTrimCallback();
private final CopyOnWriteArrayList<UIManagerListener> mUIManagerListeners =
new CopyOnWriteArrayList<>();
public UIManagerModule(
ReactApplicationContext reactContext,
ViewManagerResolver viewManagerResolver,
int minTimeLeftInFrameForNonBatchedOperationMs) {
super(reactContext);
DisplayMetricsHolder.initDisplayMetricsIfNotInitialized(reactContext);
mModuleConstants = createConstants(viewManagerResolver);
mCustomDirectEvents = UIManagerModuleConstants.directEventTypeConstants;
mViewManagerRegistry = new ViewManagerRegistry(viewManagerResolver);
reactContext.addLifecycleEventListener(this);
}
public UIManagerModule(
ReactApplicationContext reactContext,
List<ViewManager> viewManagersList,
int minTimeLeftInFrameForNonBatchedOperationMs) {
super(reactContext);
DisplayMetricsHolder.initDisplayMetricsIfNotInitialized(reactContext);
mCustomDirectEvents = MapBuilder.newHashMap();
mModuleConstants = createConstants(viewManagersList, null, mCustomDirectEvents);
mViewManagerRegistry = new ViewManagerRegistry(viewManagersList);
if (ReactBuildConfig.DEBUG) {
for (ViewManager<?, ?> viewManager : viewManagersList) {
LegacyArchitectureShadowNodeLogger.assertUnsupportedViewManager(
reactContext, viewManager.getShadowNodeClass(), viewManager.getClass().getSimpleName());
}
}
reactContext.addLifecycleEventListener(this);
}
@Override
public @NonNull String getName() {
return NAME;
}
@Override
public Map<String, Object> getConstants() {
return mModuleConstants;
}
@Override
public void initialize() {
getReactApplicationContext().registerComponentCallbacks(mMemoryTrimCallback);
getReactApplicationContext().registerComponentCallbacks(mViewManagerRegistry);
}
@Override
public void onHostResume() {}
@Override
public void onHostPause() {}
@Override
public void onHostDestroy() {}
@Override
public void invalidate() {
super.invalidate();
ReactApplicationContext reactApplicationContext = getReactApplicationContext();
reactApplicationContext.unregisterComponentCallbacks(mMemoryTrimCallback);
reactApplicationContext.unregisterComponentCallbacks(mViewManagerRegistry);
ViewManagerPropertyUpdater.clear();
}
@Override
public void markActiveTouchForTag(int surfaceId, int reactTag) {
// Not implemented for Paper.
}
@Override
public void sweepActiveTouchForTag(int surfaceId, int reactTag) {
// Not implemented for Paper.
}
/**
* This method is intended to reuse the {@link ViewManagerRegistry} with FabricUIManager. Do not
* use this method as this will be removed in the near future.
*/
@Deprecated
public ViewManagerRegistry getViewManagerRegistry_DO_NOT_USE() {
return mViewManagerRegistry;
}
private static Map<String, Object> createConstants(ViewManagerResolver viewManagerResolver) {
ReactMarker.logMarker(CREATE_UI_MANAGER_MODULE_CONSTANTS_START);
SystraceMessage.beginSection(Systrace.TRACE_TAG_REACT, "CreateUIManagerConstants")
.arg("Lazy", true)
.flush();
try {
return UIManagerModuleConstantsHelper.internal_createConstants(viewManagerResolver);
} finally {
Systrace.endSection(Systrace.TRACE_TAG_REACT);
ReactMarker.logMarker(CREATE_UI_MANAGER_MODULE_CONSTANTS_END);
}
}
public static Map<String, Object> createConstants(
List<ViewManager> viewManagers,
@Nullable Map<String, Object> customBubblingEvents,
@Nullable Map<String, Object> customDirectEvents) {
ReactMarker.logMarker(CREATE_UI_MANAGER_MODULE_CONSTANTS_START);
SystraceMessage.beginSection(Systrace.TRACE_TAG_REACT, "CreateUIManagerConstants")
.arg("Lazy", false)
.flush();
try {
return UIManagerModuleConstantsHelper.internal_createConstants(
viewManagers, customBubblingEvents, customDirectEvents);
} finally {
Systrace.endSection(Systrace.TRACE_TAG_REACT);
ReactMarker.logMarker(CREATE_UI_MANAGER_MODULE_CONSTANTS_END);
}
}
@ReactMethod(isBlockingSynchronousMethod = true)
public @Nullable WritableMap getConstantsForViewManager(String viewManagerName) {
ViewManager targetView = mViewManagerRegistry.getViewManagerIfExists(viewManagerName);
if (targetView == null) {
return null;
}
return getConstantsForViewManager(targetView, mCustomDirectEvents);
}
public static @Nullable WritableMap getConstantsForViewManager(
ViewManager viewManager, Map<String, Object> customDirectEvents) {
SystraceMessage.beginSection(
Systrace.TRACE_TAG_REACT, "UIManagerModule.getConstantsForViewManager")
.arg("ViewManager", viewManager.getName())
.arg("Lazy", true)
.flush();
try {
Map<String, Object> viewManagerConstants =
UIManagerModuleConstantsHelper.internal_createConstantsForViewManager(
viewManager, null, null, null, customDirectEvents);
if (viewManagerConstants != null) {
return Arguments.makeNativeMap(viewManagerConstants);
}
return null;
} finally {
SystraceMessage.endSection(Systrace.TRACE_TAG_REACT).flush();
}
}
@ReactMethod(isBlockingSynchronousMethod = true)
public WritableMap getDefaultEventTypes() {
return Arguments.makeNativeMap(UIManagerModuleConstantsHelper.getDefaultExportableEventTypes());
}
/** Resolves Direct Event name exposed to JS from the one known to the Native side. */
@Deprecated
public CustomEventNamesResolver getDirectEventNamesResolver() {
return new CustomEventNamesResolver() {
@Override
public @Nullable String resolveCustomEventName(@Nullable String eventName) {
return resolveCustomDirectEventName(eventName);
}
};
}
@Override
@Deprecated
@Nullable
public String resolveCustomDirectEventName(@Nullable String eventName) {
if (eventName != null) {
Map<String, String> customEventType =
(Map<String, String>) mCustomDirectEvents.get(eventName);
if (customEventType != null) {
return customEventType.get("registrationName");
}
}
return eventName;
}
@Override
public void profileNextBatch() {}
@Override
public Map<String, Long> getPerformanceCounters() {
return new java.util.HashMap<>();
}
public <T extends View> int addRootView(final T rootView) {
return addRootView(rootView, null);
}
/**
* Used by native animated module to bypass the process of updating the values through the shadow
* view hierarchy. This method will directly update native views, which means that updates for
* layout-related propertied won't be handled properly. Make sure you know what you're doing
* before calling this method :)
*/
@Override
public void synchronouslyUpdateViewOnUIThread(int tag, ReadableMap props) {}
/**
* Registers a new root view. JS can use the returned tag with manageChildren to add/remove
* children to this view.
*
* <p>Calling addRootView through UIManagerModule calls addRootView in the non-Fabric renderer,
* always. This is deprecated in favor of calling startSurface in Fabric, which must be done
* directly through the FabricUIManager.
*
* <p>Note that this must be called after getWidth()/getHeight() actually return something. See
* CatalystApplicationFragment as an example.
*
* <p>TODO(6242243): Make addRootView thread safe NB: this method is horribly not-thread-safe.
*/
@Override
public <T extends View> int addRootView(final T rootView, WritableMap initialProps) {
Systrace.beginSection(Systrace.TRACE_TAG_REACT, "UIManagerModule.addRootView");
final int tag = ReactRootViewTagGenerator.getNextRootViewTag();
Systrace.endSection(Systrace.TRACE_TAG_REACT);
return tag;
}
@Override
public <T extends View> int startSurface(
final T rootView,
final String moduleName,
final WritableMap initialProps,
int widthMeasureSpec,
int heightMeasureSpec) {
throw new UnsupportedOperationException();
}
@Override
public void stopSurface(final int surfaceId) {
throw new UnsupportedOperationException();
}
/** Unregisters a new root view. */
@ReactMethod
public void removeRootView(int rootViewTag) {}
public void updateNodeSize(int nodeViewTag, int newWidth, int newHeight) {}
public void updateInsetsPadding(int nodeViewTag, int top, int left, int bottom, int right) {}
/**
* Sets local data for a shadow node corresponded with given tag. In some cases we need a way to
* specify some environmental data to shadow node to improve layout (or do something similar), so
* {@code localData} serves these needs. For example, any stateful embedded native views may
* benefit from this. Have in mind that this data is not supposed to interfere with the state of
* the shadow view. Please respect one-directional data flow of React.
*/
public void setViewLocalData(final int tag, final Object data) {}
@ReactMethod
public void createView(int tag, String className, int rootViewTag, ReadableMap props) {
if (DEBUG) {
String message =
"(UIManager.createView) tag: " + tag + ", class: " + className + ", props: " + props;
FLog.d(ReactConstants.TAG, message);
PrinterHolder.getPrinter().logMessage(ReactDebugOverlayTags.UI_MANAGER, message);
}
}
@ReactMethod
public void updateView(final int tag, final String className, final ReadableMap props) {
if (DEBUG) {
String message =
"(UIManager.updateView) tag: " + tag + ", class: " + className + ", props: " + props;
FLog.d(ReactConstants.TAG, message);
PrinterHolder.getPrinter().logMessage(ReactDebugOverlayTags.UI_MANAGER, message);
}
}
/**
* Interface for adding/removing/moving views within a parent view from JS.
*
* @param viewTag the view tag of the parent view
* @param moveFrom a list of indices in the parent view to move views from
* @param moveTo parallel to moveFrom, a list of indices in the parent view to move views to
* @param addChildTags a list of tags of views to add to the parent
* @param addAtIndices parallel to addChildTags, a list of indices to insert those children at
* @param removeFrom a list of indices of views to permanently remove. The memory for the
* corresponding views and data structures should be reclaimed.
*/
@ReactMethod
public void manageChildren(
int viewTag,
@Nullable ReadableArray moveFrom,
@Nullable ReadableArray moveTo,
@Nullable ReadableArray addChildTags,
@Nullable ReadableArray addAtIndices,
@Nullable ReadableArray removeFrom) {
if (DEBUG) {
String message =
"(UIManager.manageChildren) tag: "
+ viewTag
+ ", moveFrom: "
+ moveFrom
+ ", moveTo: "
+ moveTo
+ ", addTags: "
+ addChildTags
+ ", atIndices: "
+ addAtIndices
+ ", removeFrom: "
+ removeFrom;
FLog.d(ReactConstants.TAG, message);
PrinterHolder.getPrinter().logMessage(ReactDebugOverlayTags.UI_MANAGER, message);
}
}
/**
* Interface for fast tracking the initial adding of views. Children view tags are assumed to be
* in order
*
* @param viewTag the view tag of the parent view
* @param childrenTags An array of tags to add to the parent in order
*/
@ReactMethod
public void setChildren(int viewTag, ReadableArray childrenTags) {
if (DEBUG) {
String message = "(UIManager.setChildren) tag: " + viewTag + ", children: " + childrenTags;
FLog.d(ReactConstants.TAG, message);
PrinterHolder.getPrinter().logMessage(ReactDebugOverlayTags.UI_MANAGER, message);
}
}
/**
* Determines the location on screen, width, and height of the given view and returns the values
* via an async callback.
*/
@ReactMethod
public void measure(int reactTag, Callback callback) {}
/**
* Determines the location on screen, width, and height of the given view relative to the device
* screen and returns the values via an async callback. This is the absolute position including
* things like the status bar
*/
@ReactMethod
public void measureInWindow(int reactTag, Callback callback) {}
/**
* Measures the view specified by tag relative to the given ancestorTag. This means that the
* returned x, y are relative to the origin x, y of the ancestor view. Results are stored in the
* given outputBuffer. We allow ancestor view and measured view to be the same, in which case the
* position always will be (0, 0) and method will only measure the view dimensions.
*
* <p>NB: Unlike {@link #measure}, this will measure relative to the view layout, not the visible
* window which can cause unexpected results when measuring relative to things like ScrollViews
* that can have offset content on the screen.
*/
@ReactMethod
public void measureLayout(
int tag, int ancestorTag, Callback errorCallback, Callback successCallback) {}
/**
* Find the touch target child native view in the supplied root view hierarchy, given a react
* target location.
*
* <p>This method is currently used only by Element Inspector DevTool.
*
* @param reactTag the tag of the root view to traverse
* @param point an array containing both X and Y target location
* @param callback will be called if with the identified child view react ID, and measurement
* info. If no view was found, callback will be invoked with no data.
*/
@ReactMethod
public void findSubviewIn(
final int reactTag, final ReadableArray point, final Callback callback) {}
/**
* Check if the first shadow node is the descendant of the second shadow node
*
* @deprecated this method will not be available in FabricUIManager class.
*/
@ReactMethod
@Deprecated
public void viewIsDescendantOf(
final int reactTag, final int ancestorReactTag, final Callback callback) {}
@ReactMethod
public void setJSResponder(int reactTag, boolean blockNativeResponder) {}
@ReactMethod
public void clearJSResponder() {}
@ReactMethod
public void dispatchViewManagerCommand(
int reactTag, Dynamic commandId, @Nullable ReadableArray commandArgs) {
// Fabric dispatchCommands should go through the JSI API - this will crash in Fabric.
@Nullable
UIManager uiManager = UIManagerHelper.getUIManager(getReactApplicationContext(), FABRIC);
if (uiManager == null) {
return;
}
if (commandId.getType() == ReadableType.Number) {
uiManager.dispatchCommand(reactTag, commandId.asInt(), commandArgs);
} else if (commandId.getType() == ReadableType.String) {
uiManager.dispatchCommand(reactTag, commandId.asString(), commandArgs);
}
}
/** Deprecated, use {@link #dispatchCommand(int, String, ReadableArray)} instead. */
@Deprecated
@Override
public void dispatchCommand(int reactTag, int commandId, @Nullable ReadableArray commandArgs) {}
@Override
public void dispatchCommand(
int reactTag, String commandId, @Nullable ReadableArray commandArgs) {}
/**
* LayoutAnimation API on Android is currently experimental. Therefore, it needs to be enabled
* explicitly in order to avoid regression in existing application written for iOS using this API.
*
* <p>Warning : This method will be removed in future version of React Native, and layout
* animation will be enabled by default, so always check for its existence before invoking it.
*
* <p>TODO(9139831) : remove this method once layout animation is fully stable.
*
* @param enabled whether layout animation is enabled or not
*/
@ReactMethod
public void setLayoutAnimationEnabledExperimental(boolean enabled) {}
/**
* Configure an animation to be used for the native layout changes, and native views creation. The
* animation will only apply during the current batch operations.
*
* <p>TODO(7728153) : animating view deletion is currently not supported.
*
* @param config the configuration of the animation for view addition/removal/update.
* @param success will be called when the animation completes, or when the animation get
* interrupted. In this case, callback parameter will be false.
* @param error will be called if there was an error processing the animation
*/
@ReactMethod
public void configureNextLayoutAnimation(ReadableMap config, Callback success, Callback error) {}
@Override
public EventDispatcher getEventDispatcher() {
return null;
}
@Override
@ReactMethod
public void sendAccessibilityEvent(int tag, int eventType) {
// TODO: T65793557 Refactor sendAccessibilityEvent to use ViewCommands
UIManager fabricUIManager = UIManagerHelper.getUIManager(getReactApplicationContext(), FABRIC);
if (fabricUIManager != null) {
fabricUIManager.sendAccessibilityEvent(tag, eventType);
}
}
/**
* Schedule a block to be executed on the UI thread. Useful if you need to execute view logic
* after all currently queued view updates have completed.
*
* @param block that contains UI logic you want to execute.
* @deprecated This method is a no-op stub retained for backward compatibility. Use {@link
* UIManagerListener} or View Commands instead.
*/
@Deprecated
@SuppressWarnings("deprecation")
public void addUIBlock(UIBlock block) {}
/**
* Schedule a block to be executed on the UI thread. Useful if you need to execute view logic
* before all currently queued view updates have completed.
*
* @param block that contains UI logic you want to execute.
* @deprecated This method is a no-op stub retained for backward compatibility. Use {@link
* UIManagerListener} or View Commands instead.
*/
@Deprecated
@SuppressWarnings("deprecation")
public void prependUIBlock(UIBlock block) {}
@Override
public void addUIManagerEventListener(UIManagerListener listener) {
mUIManagerListeners.add(listener);
}
@Override
public void removeUIManagerEventListener(UIManagerListener listener) {
mUIManagerListeners.remove(listener);
}
/**
* Given a reactTag from a component, find its root node tag, if possible. Otherwise, this will
* return 0. If the reactTag belongs to a root node, this will return the same reactTag.
*
* @deprecated this method is not going to be supported in the near future, use {@link
* ViewUtil#isRootTag(int)} to verify if a react Tag is a root or not
* <p>TODO: T63569137 Delete the method UIManagerModule.resolveRootTagFromReactTag
* @param reactTag the component tag
* @return the rootTag
*/
@Deprecated
public int resolveRootTagFromReactTag(int reactTag) {
return ViewUtil.isRootTag(reactTag) ? reactTag : 0;
}
/** Dirties the node associated with the given react tag */
public void invalidateNodeLayout(int tag) {}
/**
* Updates the styles of the {@link ReactShadowNode} based on the Measure specs received by
* parameters. offsetX and offsetY aren't used in non-Fabric, so they're ignored here.
*/
@Override
public void updateRootLayoutSpecs(
final int rootViewTag,
final int widthMeasureSpec,
final int heightMeasureSpec,
int offsetX,
int offsetY) {}
/** Listener that drops the CSSNode pool on low memory when the app is backgrounded. */
private static class MemoryTrimCallback implements ComponentCallbacks2 {
@Override
public void onTrimMemory(int level) {}
@Override
public void onConfigurationChanged(Configuration newConfig) {}
@Override
public void onLowMemory() {}
}
@Override
public @Nullable View resolveView(int tag) {
UiThreadUtil.assertOnUiThread();
return null;
}
@Override
public void receiveEvent(int reactTag, String eventName, @Nullable WritableMap event) {
receiveEvent(-1, reactTag, eventName, event);
}
@Override
public void receiveEvent(
int surfaceId, int reactTag, String eventName, @Nullable WritableMap event) {
assert false;
}
}
@@ -0,0 +1,645 @@
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
@file:Suppress("DEPRECATION", "OVERRIDE_DEPRECATION")
package com.facebook.react.uimanager
import android.annotation.SuppressLint
import android.content.ComponentCallbacks2
import android.content.res.Configuration
import android.view.View
import com.facebook.common.logging.FLog
import com.facebook.debug.holder.PrinterHolder
import com.facebook.debug.tags.ReactDebugOverlayTags
import com.facebook.react.bridge.Arguments
import com.facebook.react.bridge.Callback
import com.facebook.react.bridge.Dynamic
import com.facebook.react.bridge.LifecycleEventListener
import com.facebook.react.bridge.ReactApplicationContext
import com.facebook.react.bridge.ReactContextBaseJavaModule
import com.facebook.react.bridge.ReactMarker
import com.facebook.react.bridge.ReactMarkerConstants.CREATE_UI_MANAGER_MODULE_CONSTANTS_END
import com.facebook.react.bridge.ReactMarkerConstants.CREATE_UI_MANAGER_MODULE_CONSTANTS_START
import com.facebook.react.bridge.ReactMethod
import com.facebook.react.bridge.ReadableArray
import com.facebook.react.bridge.ReadableMap
import com.facebook.react.bridge.ReadableType
import com.facebook.react.bridge.UIManager
import com.facebook.react.bridge.UIManagerListener
import com.facebook.react.bridge.UiThreadUtil
import com.facebook.react.bridge.WritableMap
import com.facebook.react.common.MapBuilder
import com.facebook.react.common.ReactConstants
import com.facebook.react.common.annotations.UnstableReactNativeAPI
import com.facebook.react.common.annotations.internal.LegacyArchitecture
import com.facebook.react.common.annotations.internal.LegacyArchitectureLogLevel
import com.facebook.react.common.annotations.internal.LegacyArchitectureLogger
import com.facebook.react.common.build.ReactBuildConfig
import com.facebook.react.module.annotations.ReactModule
import com.facebook.react.uimanager.common.UIManagerType
import com.facebook.react.uimanager.common.ViewUtil
import com.facebook.react.uimanager.events.BlackHoleEventDispatcher
import com.facebook.react.uimanager.events.EventDispatcher
import com.facebook.react.uimanager.internal.LegacyArchitectureShadowNodeLogger
import com.facebook.systrace.Systrace
import com.facebook.systrace.SystraceMessage
import java.util.concurrent.CopyOnWriteArrayList
/**
* Native module to allow JS to create and update native Views.
*
* ## Transactional Requirement
*
* A requirement of this class is to make sure that transactional UI updates occur all at once,
* meaning that no intermediate state is ever rendered to the screen. For example, if a JS
* application update changes the background of View A to blue and the width of View B to 100, both
* need to appear at once. Practically, this means that all UI update code related to a single
* transaction must be executed as a single code block on the UI thread. Executing as multiple code
* blocks could allow the platform UI system to interrupt and render a partial UI state.
*
* To facilitate this, this module enqueues operations that are then applied to native view
* hierarchy through [NativeViewHierarchyManager] at the end of each transaction.
*
* ## CSSNodes
*
* In order to allow layout and measurement to occur on a non-UI thread, this module also operates
* on intermediate CSSNodeDEPRECATED objects that correspond to a native view. These
* CSSNodeDEPRECATED are able to calculate layout according to their styling rules, and then the
* resulting x/y/width/height of that layout is scheduled as an operation that will be applied to
* native view hierarchy at the end of current batch.
*
* TODO(5241856): Investigate memory usage of creating many small objects in UIManageModule and
* consider implementing a pool
* TODO(5483063): Don't dispatch the view hierarchy at the end of a batch if no UI changes occurred
*/
@SuppressLint("InvalidNativeModuleSuperClass")
@ReactModule(name = UIManagerModule.NAME)
@LegacyArchitecture(logLevel = LegacyArchitectureLogLevel.ERROR)
@Deprecated("This class is part of Legacy Architecture and will be removed in a future release")
@OptIn(UnstableReactNativeAPI::class)
public open class UIManagerModule : ReactContextBaseJavaModule, LifecycleEventListener, UIManager {
/** Resolves a name coming from native side to a name of the event that is exposed to JS. */
public interface CustomEventNamesResolver {
/** Returns custom event name by the provided event name. */
public fun resolveCustomEventName(eventName: String): String?
}
private val mModuleConstants: Map<String, Any>
private val mCustomDirectEvents: Map<String, Any>
private val mViewManagerRegistry: ViewManagerRegistry
private val mMemoryTrimCallback: MemoryTrimCallback = MemoryTrimCallback()
private val mUIManagerListeners: CopyOnWriteArrayList<UIManagerListener> = CopyOnWriteArrayList()
public constructor(
reactContext: ReactApplicationContext,
viewManagerResolver: ViewManagerResolver,
minTimeLeftInFrameForNonBatchedOperationMs: Int,
) : super(reactContext) {
DisplayMetricsHolder.initDisplayMetricsIfNotInitialized(reactContext)
mModuleConstants = createConstants(viewManagerResolver)
mCustomDirectEvents = UIManagerModuleConstants.directEventTypeConstants
mViewManagerRegistry = ViewManagerRegistry(viewManagerResolver)
reactContext.addLifecycleEventListener(this)
}
public constructor(
reactContext: ReactApplicationContext,
viewManagersList: List<ViewManager<*, *>>,
minTimeLeftInFrameForNonBatchedOperationMs: Int,
) : super(reactContext) {
DisplayMetricsHolder.initDisplayMetricsIfNotInitialized(reactContext)
mCustomDirectEvents = MapBuilder.newHashMap()
mModuleConstants = createConstants(viewManagersList, null, mCustomDirectEvents)
mViewManagerRegistry = ViewManagerRegistry(viewManagersList)
if (ReactBuildConfig.DEBUG) {
for (viewManager in viewManagersList) {
LegacyArchitectureShadowNodeLogger.assertUnsupportedViewManager(
reactContext,
viewManager.shadowNodeClass,
viewManager.javaClass.simpleName,
)
}
}
reactContext.addLifecycleEventListener(this)
}
override fun getName(): String = NAME
override fun getConstants(): Map<String, Any> = mModuleConstants
override fun initialize() {
getReactApplicationContext().registerComponentCallbacks(mMemoryTrimCallback)
getReactApplicationContext().registerComponentCallbacks(mViewManagerRegistry)
}
override fun onHostResume(): Unit = Unit
override fun onHostPause(): Unit = Unit
override fun onHostDestroy(): Unit = Unit
override fun invalidate() {
super.invalidate()
val reactApplicationContext = getReactApplicationContext()
reactApplicationContext.unregisterComponentCallbacks(mMemoryTrimCallback)
reactApplicationContext.unregisterComponentCallbacks(mViewManagerRegistry)
ViewManagerPropertyUpdater.clear()
}
override fun markActiveTouchForTag(surfaceId: Int, reactTag: Int) {
// Not implemented for Paper.
}
override fun sweepActiveTouchForTag(surfaceId: Int, reactTag: Int) {
// Not implemented for Paper.
}
/**
* This method is intended to reuse the [ViewManagerRegistry] with FabricUIManager. Do not use
* this method as this will be removed in the near future.
*/
@Deprecated("Do not use this method as this will be removed in the near future.")
public open fun getViewManagerRegistry_DO_NOT_USE(): ViewManagerRegistry = mViewManagerRegistry
@ReactMethod(isBlockingSynchronousMethod = true)
public open fun getConstantsForViewManager(viewManagerName: String): WritableMap? {
val targetView = mViewManagerRegistry.getViewManagerIfExists(viewManagerName) ?: return null
return UIManagerModule.getConstantsForViewManager(targetView, mCustomDirectEvents)
}
@ReactMethod(isBlockingSynchronousMethod = true)
public open fun getDefaultEventTypes(): WritableMap =
Arguments.makeNativeMap(UIManagerModuleConstantsHelper.defaultExportableEventTypes)
/** Resolves Direct Event name exposed to JS from the one known to the Native side. */
@Deprecated("Use resolveCustomDirectEventName instead.")
public open val directEventNamesResolver: CustomEventNamesResolver
get() =
object : CustomEventNamesResolver {
override fun resolveCustomEventName(eventName: String): String? {
return resolveCustomDirectEventName(eventName)
}
}
@Deprecated("This method is deprecated.")
@Suppress("UNCHECKED_CAST")
override fun resolveCustomDirectEventName(eventName: String): String? {
val customEventType = mCustomDirectEvents[eventName] as? Map<String, String>
if (customEventType != null) {
return customEventType["registrationName"]
}
return eventName
}
override fun profileNextBatch(): Unit = Unit
override val performanceCounters: Map<String, Long>
get() = HashMap()
/** Adds a root view with no initial properties. */
public open fun <T : View> addRootView(rootView: T): Int = addRootView(rootView, null)
/**
* Used by native animated module to bypass the process of updating the values through the shadow
* view hierarchy. This method will directly update native views, which means that updates for
* layout-related propertied won't be handled properly. Make sure you know what you're doing
* before calling this method :)
*/
override fun synchronouslyUpdateViewOnUIThread(reactTag: Int, props: ReadableMap): Unit = Unit
/**
* Registers a new root view. JS can use the returned tag with manageChildren to add/remove
* children to this view.
*
* Calling addRootView through UIManagerModule calls addRootView in the non-Fabric renderer,
* always. This is deprecated in favor of calling startSurface in Fabric, which must be done
* directly through the FabricUIManager.
*
* Note that this must be called after getWidth()/getHeight() actually return something. See
* CatalystApplicationFragment as an example.
*
* TODO(6242243): Make addRootView thread safe NB: this method is horribly not-thread-safe.
*/
override fun <T : View> addRootView(rootView: T, initialProps: WritableMap?): Int {
Systrace.beginSection(Systrace.TRACE_TAG_REACT, "UIManagerModule.addRootView")
val tag = ReactRootViewTagGenerator.getNextRootViewTag()
Systrace.endSection(Systrace.TRACE_TAG_REACT)
return tag
}
override fun <T : View?> startSurface(
rootView: T,
moduleName: String,
initialProps: WritableMap?,
widthMeasureSpec: Int,
heightMeasureSpec: Int,
): Int {
throw UnsupportedOperationException()
}
override fun stopSurface(surfaceId: Int) {
throw UnsupportedOperationException()
}
/** Unregisters a new root view. */
@ReactMethod public open fun removeRootView(rootViewTag: Int): Unit = Unit
/** Updates the size of a node. */
public open fun updateNodeSize(nodeViewTag: Int, newWidth: Int, newHeight: Int): Unit = Unit
/** Updates the insets padding for a node. */
public open fun updateInsetsPadding(
nodeViewTag: Int,
top: Int,
left: Int,
bottom: Int,
right: Int,
): Unit = Unit
/**
* Sets local data for a shadow node corresponded with given tag. In some cases we need a way to
* specify some environmental data to shadow node to improve layout (or do something similar), so
* [data] serves these needs. For example, any stateful embedded native views may benefit from
* this. Have in mind that this data is not supposed to interfere with the state of the shadow
* view. Please respect one-directional data flow of React.
*/
public open fun setViewLocalData(tag: Int, data: Any): Unit = Unit
@ReactMethod
public open fun createView(tag: Int, className: String, rootViewTag: Int, props: ReadableMap?) {
if (DEBUG) {
val message = "(UIManager.createView) tag: $tag, class: $className, props: $props"
FLog.d(ReactConstants.TAG, message)
PrinterHolder.printer.logMessage(ReactDebugOverlayTags.UI_MANAGER, message)
}
}
@ReactMethod
public open fun updateView(tag: Int, className: String, props: ReadableMap?) {
if (DEBUG) {
val message = "(UIManager.updateView) tag: $tag, class: $className, props: $props"
FLog.d(ReactConstants.TAG, message)
PrinterHolder.printer.logMessage(ReactDebugOverlayTags.UI_MANAGER, message)
}
}
/**
* Interface for adding/removing/moving views within a parent view from JS.
*
* @param viewTag the view tag of the parent view
* @param moveFrom a list of indices in the parent view to move views from
* @param moveTo parallel to moveFrom, a list of indices in the parent view to move views to
* @param addChildTags a list of tags of views to add to the parent
* @param addAtIndices parallel to addChildTags, a list of indices to insert those children at
* @param removeFrom a list of indices of views to permanently remove. The memory for the
* corresponding views and data structures should be reclaimed.
*/
@ReactMethod
public open fun manageChildren(
viewTag: Int,
moveFrom: ReadableArray?,
moveTo: ReadableArray?,
addChildTags: ReadableArray?,
addAtIndices: ReadableArray?,
removeFrom: ReadableArray?,
) {
if (DEBUG) {
val message =
"(UIManager.manageChildren) tag: $viewTag, moveFrom: $moveFrom, moveTo: $moveTo, addTags: $addChildTags, atIndices: $addAtIndices, removeFrom: $removeFrom"
FLog.d(ReactConstants.TAG, message)
PrinterHolder.printer.logMessage(ReactDebugOverlayTags.UI_MANAGER, message)
}
}
/**
* Interface for fast tracking the initial adding of views. Children view tags are assumed to be
* in order.
*
* @param viewTag the view tag of the parent view
* @param childrenTags an array of tags to add to the parent in order
*/
@ReactMethod
public open fun setChildren(viewTag: Int, childrenTags: ReadableArray) {
if (DEBUG) {
val message = "(UIManager.setChildren) tag: $viewTag, children: $childrenTags"
FLog.d(ReactConstants.TAG, message)
PrinterHolder.printer.logMessage(ReactDebugOverlayTags.UI_MANAGER, message)
}
}
/**
* Determines the location on screen, width, and height of the given view and returns the values
* via an async callback.
*/
@ReactMethod public open fun measure(reactTag: Int, callback: Callback): Unit = Unit
/**
* Determines the location on screen, width, and height of the given view relative to the device
* screen and returns the values via an async callback. This is the absolute position including
* things like the status bar.
*/
@ReactMethod public open fun measureInWindow(reactTag: Int, callback: Callback): Unit = Unit
/**
* Measures the view specified by tag relative to the given ancestorTag. This means that the
* returned x, y are relative to the origin x, y of the ancestor view. Results are stored in the
* given outputBuffer. We allow ancestor view and measured view to be the same, in which case the
* position always will be (0, 0) and method will only measure the view dimensions.
*
* NB: Unlike [measure], this will measure relative to the view layout, not the visible window
* which can cause unexpected results when measuring relative to things like ScrollViews that can
* have offset content on the screen.
*/
@ReactMethod
public open fun measureLayout(
tag: Int,
ancestorTag: Int,
errorCallback: Callback,
successCallback: Callback,
): Unit = Unit
/**
* Find the touch target child native view in the supplied root view hierarchy, given a react
* target location.
*
* This method is currently used only by Element Inspector DevTool.
*
* @param reactTag the tag of the root view to traverse
* @param point an array containing both X and Y target location
* @param callback will be called if with the identified child view react ID, and measurement
* info. If no view was found, callback will be invoked with no data.
*/
@ReactMethod
public open fun findSubviewIn(reactTag: Int, point: ReadableArray, callback: Callback): Unit =
Unit
/**
* Check if the first shadow node is the descendant of the second shadow node.
*
* @deprecated this method will not be available in FabricUIManager class.
*/
@ReactMethod
@Deprecated("This method will not be available in FabricUIManager class.")
public open fun viewIsDescendantOf(
reactTag: Int,
ancestorReactTag: Int,
callback: Callback,
): Unit = Unit
@ReactMethod
public open fun setJSResponder(reactTag: Int, blockNativeResponder: Boolean): Unit = Unit
@ReactMethod public open fun clearJSResponder(): Unit = Unit
@ReactMethod
public open fun dispatchViewManagerCommand(
reactTag: Int,
commandId: Dynamic,
commandArgs: ReadableArray?,
) {
// Fabric dispatchCommands should go through the JSI API - this will crash in Fabric.
val uiManager: UIManager? =
UIManagerHelper.getUIManager(getReactApplicationContext(), UIManagerType.FABRIC)
if (uiManager == null) {
return
}
if (commandId.type == ReadableType.Number) {
uiManager.dispatchCommand(reactTag, commandId.asInt(), commandArgs)
} else if (commandId.type == ReadableType.String) {
val command = commandId.asString() ?: return
uiManager.dispatchCommand(reactTag, command, commandArgs)
}
}
/** Deprecated, use [dispatchCommand] with String commandId instead. */
@Deprecated("Use dispatchCommand(int, String, ReadableArray) instead.")
override fun dispatchCommand(reactTag: Int, commandId: Int, commandArgs: ReadableArray?): Unit =
Unit
override fun dispatchCommand(
reactTag: Int,
commandId: String,
commandArgs: ReadableArray?,
): Unit = Unit
/**
* LayoutAnimation API on Android is currently experimental. Therefore, it needs to be enabled
* explicitly in order to avoid regression in existing application written for iOS using this API.
*
* Warning : This method will be removed in future version of React Native, and layout animation
* will be enabled by default, so always check for its existence before invoking it.
*
* @param enabled whether layout animation is enabled or not
*
* TODO(9139831) : remove this method once layout animation is fully stable.
*/
@ReactMethod public open fun setLayoutAnimationEnabledExperimental(enabled: Boolean): Unit = Unit
/**
* Configure an animation to be used for the native layout changes, and native views creation. The
* animation will only apply during the current batch operations.
*
* @param config the configuration of the animation for view addition/removal/update.
* @param success will be called when the animation completes, or when the animation get
* interrupted. In this case, callback parameter will be false.
* @param error will be called if there was an error processing the animation
*
* TODO(7728153) : animating view deletion is currently not supported.
*/
@ReactMethod
public open fun configureNextLayoutAnimation(
config: ReadableMap,
success: Callback,
error: Callback,
): Unit = Unit
// Java original returned null, but the UIManager interface requires non-null.
// BlackHoleEventDispatcher silently discards events, matching the legacy no-op behavior.
override val eventDispatcher: EventDispatcher
get() = BlackHoleEventDispatcher
@ReactMethod
override fun sendAccessibilityEvent(reactTag: Int, eventType: Int) {
// TODO: T65793557 Refactor sendAccessibilityEvent to use ViewCommands
val fabricUIManager: UIManager? =
UIManagerHelper.getUIManager(getReactApplicationContext(), UIManagerType.FABRIC)
if (fabricUIManager != null) {
fabricUIManager.sendAccessibilityEvent(reactTag, eventType)
}
}
/**
* Schedule a block to be executed on the UI thread. Useful if you need to execute view logic
* after all currently queued view updates have completed.
*
* @param block that contains UI logic you want to execute.
* @deprecated This method is a no-op stub retained for backward compatibility. Use
* [UIManagerListener] or View Commands instead.
*/
@Deprecated("This method is a no-op stub. Use UIManagerListener or View Commands instead.")
public open fun addUIBlock(block: UIBlock): Unit = Unit
/**
* Schedule a block to be executed on the UI thread. Useful if you need to execute view logic
* before all currently queued view updates have completed.
*
* @param block that contains UI logic you want to execute.
* @deprecated This method is a no-op stub retained for backward compatibility. Use
* [UIManagerListener] or View Commands instead.
*/
@Deprecated("This method is a no-op stub. Use UIManagerListener or View Commands instead.")
public open fun prependUIBlock(block: UIBlock): Unit = Unit
override fun addUIManagerEventListener(listener: UIManagerListener) {
mUIManagerListeners.add(listener)
}
override fun removeUIManagerEventListener(listener: UIManagerListener) {
mUIManagerListeners.remove(listener)
}
/**
* Given a reactTag from a component, find its root node tag, if possible. Otherwise, this will
* return 0. If the reactTag belongs to a root node, this will return the same reactTag.
*
* @param reactTag the component tag
* @return the rootTag
* @deprecated this method is not going to be supported in the near future, use
* [ViewUtil.isRootTag] to verify if a react Tag is a root or not
*
* TODO: T63569137 Delete the method UIManagerModule.resolveRootTagFromReactTag
*/
@Deprecated("Use ViewUtil.isRootTag(int) to verify if a react Tag is a root or not.")
public open fun resolveRootTagFromReactTag(reactTag: Int): Int =
if (ViewUtil.isRootTag(reactTag)) reactTag else 0
/** Dirties the node associated with the given react tag. */
public open fun invalidateNodeLayout(tag: Int): Unit = Unit
/**
* Updates the styles of the [ReactShadowNode] based on the Measure specs received by parameters.
* offsetX and offsetY aren't used in non-Fabric, so they're ignored here.
*/
override fun updateRootLayoutSpecs(
rootTag: Int,
widthMeasureSpec: Int,
heightMeasureSpec: Int,
offsetX: Int,
offsetY: Int,
): Unit = Unit
/** Listener that drops the CSSNode pool on low memory when the app is backgrounded. */
private class MemoryTrimCallback : ComponentCallbacks2 {
override fun onTrimMemory(level: Int): Unit = Unit
override fun onConfigurationChanged(newConfig: Configuration): Unit = Unit
override fun onLowMemory(): Unit = Unit
}
override fun resolveView(reactTag: Int): View? {
UiThreadUtil.assertOnUiThread()
return null
}
override fun receiveEvent(reactTag: Int, eventName: String, event: WritableMap?) {
receiveEvent(-1, reactTag, eventName, event)
}
override fun receiveEvent(surfaceId: Int, reactTag: Int, eventName: String, event: WritableMap?) {
assert(false)
}
public companion object {
/** The name of this module. */
public const val NAME: String = "UIManager"
/** Tag for logging. */
@JvmField public val TAG: String = UIManagerModule::class.java.simpleName
private val DEBUG: Boolean =
PrinterHolder.printer.shouldDisplayLogMessage(ReactDebugOverlayTags.UI_MANAGER)
init {
LegacyArchitectureLogger.assertLegacyArchitecture(
"UIManagerModule",
LegacyArchitectureLogLevel.ERROR,
)
}
private fun createConstants(viewManagerResolver: ViewManagerResolver): Map<String, Any> {
ReactMarker.logMarker(CREATE_UI_MANAGER_MODULE_CONSTANTS_START)
SystraceMessage.beginSection(Systrace.TRACE_TAG_REACT, "CreateUIManagerConstants")
.arg("Lazy", true)
.flush()
try {
return UIManagerModuleConstantsHelper.createConstants(viewManagerResolver)
} finally {
Systrace.endSection(Systrace.TRACE_TAG_REACT)
ReactMarker.logMarker(CREATE_UI_MANAGER_MODULE_CONSTANTS_END)
}
}
/** Creates constants for the given list of view managers. */
@JvmStatic
public fun createConstants(
viewManagers: List<ViewManager<*, *>>,
customBubblingEvents: Map<String, Any>?,
customDirectEvents: Map<String, Any>?,
): Map<String, Any> {
ReactMarker.logMarker(CREATE_UI_MANAGER_MODULE_CONSTANTS_START)
SystraceMessage.beginSection(Systrace.TRACE_TAG_REACT, "CreateUIManagerConstants")
.arg("Lazy", false)
.flush()
try {
@Suppress("UNCHECKED_CAST")
return UIManagerModuleConstantsHelper.createConstants(
viewManagers as List<ViewManager<in Nothing, in Nothing>>,
customBubblingEvents as? MutableMap<String, Any>,
customDirectEvents as? MutableMap<String, Any>,
)
} finally {
Systrace.endSection(Systrace.TRACE_TAG_REACT)
ReactMarker.logMarker(CREATE_UI_MANAGER_MODULE_CONSTANTS_END)
}
}
/** Returns constants for the given view manager. */
@JvmStatic
public fun getConstantsForViewManager(
viewManager: ViewManager<*, *>,
customDirectEvents: Map<String, Any>,
): WritableMap? {
SystraceMessage.beginSection(
Systrace.TRACE_TAG_REACT,
"UIManagerModule.getConstantsForViewManager",
)
.arg("ViewManager", viewManager.name)
.arg("Lazy", true)
.flush()
try {
@Suppress("UNCHECKED_CAST")
val viewManagerConstants =
UIManagerModuleConstantsHelper.createConstantsForViewManager(
viewManager as ViewManager<in Nothing, in Nothing>,
null,
null,
null,
customDirectEvents as? MutableMap<String, Any>,
)
return Arguments.makeNativeMap(viewManagerConstants)
} finally {
SystraceMessage.endSection(Systrace.TRACE_TAG_REACT).flush()
}
}
}
}
@@ -27,8 +27,8 @@ import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.ArgumentCaptor
import org.mockito.ArgumentMatchers.any
import org.mockito.ArgumentMatchers.anyInt
import org.mockito.ArgumentMatchers.anyString
import org.mockito.ArgumentMatchers.eq
import org.mockito.kotlin.atMost
import org.mockito.kotlin.mock
@@ -46,6 +46,12 @@ import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
class NativeAnimatedNodeTraversalTest {
@Suppress("UNCHECKED_CAST")
private fun <T> capture(captor: ArgumentCaptor<T>): T = captor.capture() ?: null as T
@Suppress("UNCHECKED_CAST")
private fun <T> anyNonNull(): T = org.mockito.ArgumentMatchers.any<T>() ?: null as T
private var frameTimeNanos: Long = 0L
private lateinit var reactApplicationContextMock: ReactApplicationContext
private lateinit var catalystInstanceMock: CatalystInstance
@@ -97,8 +103,7 @@ class NativeAnimatedNodeTraversalTest {
}
}
}
whenever(uiManagerMock.resolveCustomDirectEventName(any(String::class.java))).thenAnswer {
invocation ->
whenever(uiManagerMock.resolveCustomDirectEventName(anyString())).thenAnswer { invocation ->
val arg = invocation.arguments[0].toString()
"on${arg.substring(3)}"
}
@@ -150,7 +155,7 @@ class NativeAnimatedNodeTraversalTest {
for (i in 0 until frames.size()) {
reset(uiManagerMock)
nativeAnimatedNodesManager.runUpdates(nextFrameTime())
verify(uiManagerMock).synchronouslyUpdateViewOnUIThread(eq(1000), stylesCaptor.capture())
verify(uiManagerMock).synchronouslyUpdateViewOnUIThread(eq(1000), capture(stylesCaptor))
assertThat(stylesCaptor.value.getDouble("opacity")).isEqualTo(frames.getDouble(i))
}
@@ -179,7 +184,7 @@ class NativeAnimatedNodeTraversalTest {
for (i in 0 until frames.size()) {
reset(uiManagerMock)
nativeAnimatedNodesManager.runUpdates(nextFrameTime())
verify(uiManagerMock).synchronouslyUpdateViewOnUIThread(eq(1000), stylesCaptor.capture())
verify(uiManagerMock).synchronouslyUpdateViewOnUIThread(eq(1000), capture(stylesCaptor))
if (i < frames.size() - 1 || iteration == 1) {
assertThat(stylesCaptor.value.getDouble("opacity")).isEqualTo(frames.getDouble(i))
@@ -213,7 +218,7 @@ class NativeAnimatedNodeTraversalTest {
for (i in 0 until frames.size()) {
reset(uiManagerMock)
nativeAnimatedNodesManager.runUpdates(nextFrameTime())
verify(uiManagerMock).synchronouslyUpdateViewOnUIThread(eq(1000), stylesCaptor.capture())
verify(uiManagerMock).synchronouslyUpdateViewOnUIThread(eq(1000), capture(stylesCaptor))
assertThat(stylesCaptor.value.getDouble("opacity")).isEqualTo(frames.getDouble(i))
}
}
@@ -294,7 +299,7 @@ class NativeAnimatedNodeTraversalTest {
reset(uiManagerMock)
nativeAnimatedNodesManager.runUpdates(nextFrameTime())
verify(uiManagerMock).synchronouslyUpdateViewOnUIThread(eq(1000), stylesCaptor.capture())
verify(uiManagerMock).synchronouslyUpdateViewOnUIThread(eq(1000), capture(stylesCaptor))
assertThat(stylesCaptor.value.getDouble("opacity")).isEqualTo(0.0)
var previousValue: Double = 0.0
@@ -305,7 +310,7 @@ class NativeAnimatedNodeTraversalTest {
reset(uiManagerMock)
nativeAnimatedNodesManager.runUpdates(nextFrameTime())
verify(uiManagerMock, atMost(1))
.synchronouslyUpdateViewOnUIThread(eq(1000), stylesCaptor.capture())
.synchronouslyUpdateViewOnUIThread(eq(1000), capture(stylesCaptor))
val currentValue: Double = stylesCaptor.value.getDouble("opacity")
if (currentValue > 1.0) {
wasGreaterThanOne = true
@@ -419,7 +424,7 @@ class NativeAnimatedNodeTraversalTest {
reset(uiManagerMock)
nativeAnimatedNodesManager.runUpdates(nextFrameTime())
verify(uiManagerMock).synchronouslyUpdateViewOnUIThread(eq(1000), stylesCaptor.capture())
verify(uiManagerMock).synchronouslyUpdateViewOnUIThread(eq(1000), capture(stylesCaptor))
assertThat(stylesCaptor.value.getDouble("opacity")).isEqualTo(0.0)
var previousValue = 0.0
@@ -431,7 +436,7 @@ class NativeAnimatedNodeTraversalTest {
reset(uiManagerMock)
nativeAnimatedNodesManager.runUpdates(nextFrameTime())
verify(uiManagerMock, atMost(1))
.synchronouslyUpdateViewOnUIThread(eq(1000), stylesCaptor.capture())
.synchronouslyUpdateViewOnUIThread(eq(1000), capture(stylesCaptor))
val currentValue: Double = stylesCaptor.value.getDouble("opacity")
if (currentValue > 1.0) {
wasGreaterThanOne = true
@@ -482,7 +487,7 @@ class NativeAnimatedNodeTraversalTest {
reset(uiManagerMock)
nativeAnimatedNodesManager.runUpdates(nextFrameTime())
verify(uiManagerMock, atMost(1))
.synchronouslyUpdateViewOnUIThread(eq(1000), stylesCaptor.capture())
.synchronouslyUpdateViewOnUIThread(eq(1000), capture(stylesCaptor))
var previousValue: Double = stylesCaptor.value.getDouble("opacity")
var previousDiff: Double = Double.POSITIVE_INFINITY
/* run 3 secs of animation */
@@ -490,7 +495,7 @@ class NativeAnimatedNodeTraversalTest {
reset(uiManagerMock)
nativeAnimatedNodesManager.runUpdates(nextFrameTime())
verify(uiManagerMock, atMost(1))
.synchronouslyUpdateViewOnUIThread(eq(1000), stylesCaptor.capture())
.synchronouslyUpdateViewOnUIThread(eq(1000), capture(stylesCaptor))
val currentValue: Double = stylesCaptor.value.getDouble("opacity")
val currentDiff: Double = currentValue - previousValue
// verify monotonicity
@@ -533,7 +538,7 @@ class NativeAnimatedNodeTraversalTest {
reset(uiManagerMock)
nativeAnimatedNodesManager.runUpdates(nextFrameTime())
verify(uiManagerMock, atMost(1))
.synchronouslyUpdateViewOnUIThread(eq(1000), stylesCaptor.capture())
.synchronouslyUpdateViewOnUIThread(eq(1000), capture(stylesCaptor))
var previousValue: Double = stylesCaptor.value.getDouble("opacity")
val initialValue: Double = stylesCaptor.value.getDouble("opacity")
var didComeToRest = false
@@ -543,7 +548,7 @@ class NativeAnimatedNodeTraversalTest {
reset(uiManagerMock)
nativeAnimatedNodesManager.runUpdates(nextFrameTime())
verify(uiManagerMock, atMost(1))
.synchronouslyUpdateViewOnUIThread(eq(1000), stylesCaptor.capture())
.synchronouslyUpdateViewOnUIThread(eq(1000), capture(stylesCaptor))
val currentValue: Double = stylesCaptor.value.getDouble("opacity")
val currentDiff: Double = currentValue - previousValue
// Test to see if it reset after coming to rest (i.e. dropped back to )
@@ -591,7 +596,7 @@ class NativeAnimatedNodeTraversalTest {
reset(animationCallback)
nativeAnimatedNodesManager.runUpdates(nextFrameTime())
verify(animationCallback).invoke(callbackResponseCaptor.capture())
verify(animationCallback).invoke(capture(callbackResponseCaptor))
assertThat(callbackResponseCaptor.value.hasKey("finished")).isTrue
assertThat(callbackResponseCaptor.value.getBoolean("finished")).isTrue
@@ -665,12 +670,12 @@ class NativeAnimatedNodeTraversalTest {
reset(uiManagerMock)
nativeAnimatedNodesManager.runUpdates(nextFrameTime())
verify(uiManagerMock).synchronouslyUpdateViewOnUIThread(eq(50), stylesCaptor.capture())
verify(uiManagerMock).synchronouslyUpdateViewOnUIThread(eq(50), capture(stylesCaptor))
assertThat(stylesCaptor.value.getDouble("translateX")).isEqualTo(1100.0)
reset(uiManagerMock)
nativeAnimatedNodesManager.runUpdates(nextFrameTime())
verify(uiManagerMock).synchronouslyUpdateViewOnUIThread(eq(50), stylesCaptor.capture())
verify(uiManagerMock).synchronouslyUpdateViewOnUIThread(eq(50), capture(stylesCaptor))
assertThat(stylesCaptor.value.getDouble("translateX")).isEqualTo(1111.0)
reset(uiManagerMock)
@@ -703,12 +708,12 @@ class NativeAnimatedNodeTraversalTest {
reset(uiManagerMock)
nativeAnimatedNodesManager.runUpdates(nextFrameTime())
verify(uiManagerMock).synchronouslyUpdateViewOnUIThread(eq(50), stylesCaptor.capture())
verify(uiManagerMock).synchronouslyUpdateViewOnUIThread(eq(50), capture(stylesCaptor))
assertThat(stylesCaptor.value.getDouble("translateX")).isEqualTo(1100.0)
reset(uiManagerMock)
nativeAnimatedNodesManager.runUpdates(nextFrameTime())
verify(uiManagerMock).synchronouslyUpdateViewOnUIThread(eq(50), stylesCaptor.capture())
verify(uiManagerMock).synchronouslyUpdateViewOnUIThread(eq(50), capture(stylesCaptor))
assertThat(stylesCaptor.value.getDouble("translateX")).isEqualTo(1101.0)
reset(uiManagerMock)
@@ -752,13 +757,13 @@ class NativeAnimatedNodeTraversalTest {
reset(uiManagerMock)
nativeAnimatedNodesManager.runUpdates(nextFrameTime())
verify(uiManagerMock).synchronouslyUpdateViewOnUIThread(eq(50), stylesCaptor.capture())
verify(uiManagerMock).synchronouslyUpdateViewOnUIThread(eq(50), capture(stylesCaptor))
assertThat(stylesCaptor.value.getDouble("translateX")).isEqualTo(1100.0)
for (i in 1 until secondFrames.size()) {
reset(uiManagerMock)
nativeAnimatedNodesManager.runUpdates(nextFrameTime())
verify(uiManagerMock).synchronouslyUpdateViewOnUIThread(eq(50), stylesCaptor.capture())
verify(uiManagerMock).synchronouslyUpdateViewOnUIThread(eq(50), capture(stylesCaptor))
assertThat(stylesCaptor.value.getDouble("translateX"))
.isEqualTo(1200.0 + secondFrames.getDouble(i) * 10.0)
}
@@ -818,12 +823,12 @@ class NativeAnimatedNodeTraversalTest {
reset(uiManagerMock)
nativeAnimatedNodesManager.runUpdates(nextFrameTime())
verify(uiManagerMock).synchronouslyUpdateViewOnUIThread(eq(50), stylesCaptor.capture())
verify(uiManagerMock).synchronouslyUpdateViewOnUIThread(eq(50), capture(stylesCaptor))
assertThat(stylesCaptor.value.getDouble("translateX")).isEqualTo(5.0)
reset(uiManagerMock)
nativeAnimatedNodesManager.runUpdates(nextFrameTime())
verify(uiManagerMock).synchronouslyUpdateViewOnUIThread(eq(50), stylesCaptor.capture())
verify(uiManagerMock).synchronouslyUpdateViewOnUIThread(eq(50), capture(stylesCaptor))
assertThat(stylesCaptor.value.getDouble("translateX")).isEqualTo(20.0)
reset(uiManagerMock)
@@ -857,13 +862,13 @@ class NativeAnimatedNodeTraversalTest {
nativeAnimatedNodesManager.runUpdates(nextFrameTime())
nativeAnimatedNodesManager.runUpdates(nextFrameTime())
verify(uiManagerMock, times(2))
.synchronouslyUpdateViewOnUIThread(anyInt(), any(ReadableMap::class.java))
.synchronouslyUpdateViewOnUIThread(anyInt(), anyNonNull<ReadableMap>())
verifyNoMoreInteractions(animationCallback)
reset(animationCallback)
reset(uiManagerMock)
nativeAnimatedNodesManager.stopAnimation(404)
verify(animationCallback).invoke(callbackResponseCaptor.capture())
verify(animationCallback).invoke(capture(callbackResponseCaptor))
verifyNoMoreInteractions(animationCallback)
verifyNoMoreInteractions(uiManagerMock)
@@ -947,7 +952,7 @@ class NativeAnimatedNodeTraversalTest {
for (i in 0 until frames.size()) {
reset(uiManagerMock)
nativeAnimatedNodesManager.runUpdates(nextFrameTime())
verify(uiManagerMock).synchronouslyUpdateViewOnUIThread(eq(50), stylesCaptor.capture())
verify(uiManagerMock).synchronouslyUpdateViewOnUIThread(eq(50), capture(stylesCaptor))
assertThat(stylesCaptor.value.getDouble("opacity")).isEqualTo(frames.getDouble(i))
}
@@ -998,7 +1003,7 @@ class NativeAnimatedNodeTraversalTest {
reset(uiManagerMock)
nativeAnimatedNodesManager.runUpdates(nextFrameTime())
verify(uiManagerMock).synchronouslyUpdateViewOnUIThread(eq(viewTag), stylesCaptor.capture())
verify(uiManagerMock).synchronouslyUpdateViewOnUIThread(eq(viewTag), capture(stylesCaptor))
assertThat(stylesCaptor.value.getDouble("opacity")).isEqualTo(10.0)
}
@@ -1036,7 +1041,7 @@ class NativeAnimatedNodeTraversalTest {
reset(uiManagerMock)
nativeAnimatedNodesManager.runUpdates(nextFrameTime())
verify(uiManagerMock).synchronouslyUpdateViewOnUIThread(eq(viewTag), stylesCaptor.capture())
verify(uiManagerMock).synchronouslyUpdateViewOnUIThread(eq(viewTag), capture(stylesCaptor))
assertThat(stylesCaptor.value.getDouble("opacity")).isEqualTo(0.0)
}
@@ -1071,7 +1076,7 @@ class NativeAnimatedNodeTraversalTest {
reset(uiManagerMock)
nativeAnimatedNodesManager.runUpdates(nextFrameTime())
verify(uiManagerMock).synchronouslyUpdateViewOnUIThread(eq(viewTag), stylesCaptor.capture())
verify(uiManagerMock).synchronouslyUpdateViewOnUIThread(eq(viewTag), capture(stylesCaptor))
assertThat(stylesCaptor.value.getDouble("opacity")).isEqualTo(10.0)
}
@@ -1097,7 +1102,8 @@ class NativeAnimatedNodeTraversalTest {
reset(uiManagerMock)
nativeAnimatedNodesManager.restoreDefaultValues(propsNodeTag)
verify(uiManagerMock, never()).synchronouslyUpdateViewOnUIThread(anyInt(), any<ReadableMap>())
verify(uiManagerMock, never())
.synchronouslyUpdateViewOnUIThread(anyInt(), anyNonNull<ReadableMap>())
}
/**
@@ -1166,7 +1172,7 @@ class NativeAnimatedNodeTraversalTest {
reset(uiManagerMock)
nativeAnimatedNodesManager.runUpdates(nextFrameTime())
verify(uiManagerMock).synchronouslyUpdateViewOnUIThread(eq(1000), stylesCaptor.capture())
verify(uiManagerMock).synchronouslyUpdateViewOnUIThread(eq(1000), capture(stylesCaptor))
assertThat(stylesCaptor.value.getDouble("translateX")).isEqualTo(0.0)
// update "toValue" to 100, we expect tracking animation to animate now from 0 to 100 in 5
@@ -1178,7 +1184,7 @@ class NativeAnimatedNodeTraversalTest {
for (i in 0 until frames.size()) {
reset(uiManagerMock)
nativeAnimatedNodesManager.runUpdates(nextFrameTime())
verify(uiManagerMock).synchronouslyUpdateViewOnUIThread(eq(1000), stylesCaptor.capture())
verify(uiManagerMock).synchronouslyUpdateViewOnUIThread(eq(1000), capture(stylesCaptor))
assertThat(stylesCaptor.value.getDouble("translateX")).isEqualTo(frames.getDouble(i) * 100.0)
}
@@ -1191,7 +1197,7 @@ class NativeAnimatedNodeTraversalTest {
for (i in 0 until 2) {
reset(uiManagerMock)
nativeAnimatedNodesManager.runUpdates(nextFrameTime())
verify(uiManagerMock).synchronouslyUpdateViewOnUIThread(eq(1000), stylesCaptor.capture())
verify(uiManagerMock).synchronouslyUpdateViewOnUIThread(eq(1000), capture(stylesCaptor))
assertThat(stylesCaptor.value.getDouble("translateX"))
.isEqualTo(100 * (1 - frames.getDouble(i)))
}
@@ -1209,7 +1215,7 @@ class NativeAnimatedNodeTraversalTest {
for (i in 0 until frames.size()) {
reset(uiManagerMock)
nativeAnimatedNodesManager.runUpdates(nextFrameTime())
verify(uiManagerMock).synchronouslyUpdateViewOnUIThread(eq(1000), stylesCaptor.capture())
verify(uiManagerMock).synchronouslyUpdateViewOnUIThread(eq(1000), capture(stylesCaptor))
assertThat(stylesCaptor.value.getDouble("translateX"))
.isEqualTo(50.0 + 50.0 * frames.getDouble(i))
}
@@ -1238,7 +1244,7 @@ class NativeAnimatedNodeTraversalTest {
nativeAnimatedNodesManager.runUpdates(nextFrameTime())
}
verify(uiManagerMock, times(frames.size()))
.synchronouslyUpdateViewOnUIThread(eq(1000), any(ReadableMap::class.java))
.synchronouslyUpdateViewOnUIThread(eq(1000), anyNonNull<ReadableMap>())
// the animation has completed, we expect no updates to be done
reset(uiManagerMock)
@@ -1257,7 +1263,7 @@ class NativeAnimatedNodeTraversalTest {
nativeAnimatedNodesManager.runUpdates(nextFrameTime())
}
verify(uiManagerMock, times(frames.size()))
.synchronouslyUpdateViewOnUIThread(eq(1000), any(ReadableMap::class.java))
.synchronouslyUpdateViewOnUIThread(eq(1000), anyNonNull<ReadableMap>())
// the animation has completed, we expect no updates to be done
reset(uiManagerMock)