Format Java code in xplat/js/react-native-github

Summary:
This diff formats the Java class files inside xplat/js/react-native-github. Since google-java-format was enabled in D16071401 we want to codemode the existing code so that users don't have to deal with formatter lint noise at diff-time.

```arc f --paths-cmd 'hg files -I "**/*.java"'```

drop-conflicts

Reviewed By: cpojer

Differential Revision: D16071725

fbshipit-source-id: fc6e3852e45742c109f0c5ac4065d64201c74204
This commit is contained in:
Oleksandr Melnykov 2019-07-02 04:13:35 -07:00 коммит произвёл Facebook Github Bot
Родитель 61e95e5cbf
Коммит 6c0f73b322
681 изменённых файлов: 14085 добавлений и 16368 удалений

Просмотреть файл

@ -1,18 +1,14 @@
/** /**
* Copyright (c) Facebook, Inc. and its affiliates. * Copyright (c) Facebook, Inc. and its affiliates.
* *
* This source code is licensed under the MIT license found in the * <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* LICENSE file in the root directory of this source tree. * directory of this source tree.
*
*/ */
package com.facebook.react.uiapp; package com.facebook.react.uiapp;
import android.os.Bundle; import android.os.Bundle;
import com.facebook.react.ReactActivity; import com.facebook.react.ReactActivity;
import com.facebook.react.ReactActivityDelegate; import com.facebook.react.ReactActivityDelegate;
import javax.annotation.Nullable; import javax.annotation.Nullable;
public class RNTesterActivity extends ReactActivity { public class RNTesterActivity extends ReactActivity {
@ -31,7 +27,8 @@ public class RNTesterActivity extends ReactActivity {
// Get remote param before calling super which uses it // Get remote param before calling super which uses it
Bundle bundle = mActivity.getIntent().getExtras(); Bundle bundle = mActivity.getIntent().getExtras();
if (bundle != null && bundle.containsKey(PARAM_ROUTE)) { if (bundle != null && bundle.containsKey(PARAM_ROUTE)) {
String routeUri = new StringBuilder("rntester://example/") String routeUri =
new StringBuilder("rntester://example/")
.append(bundle.getString(PARAM_ROUTE)) .append(bundle.getString(PARAM_ROUTE))
.append("Example") .append("Example")
.toString(); .toString();

Просмотреть файл

@ -1,27 +1,24 @@
/** /**
* Copyright (c) Facebook, Inc. and its affiliates. * Copyright (c) Facebook, Inc. and its affiliates.
* *
* This source code is licensed under the MIT license found in the * <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* LICENSE file in the root directory of this source tree. * directory of this source tree.
*
*/ */
package com.facebook.react.uiapp; package com.facebook.react.uiapp;
import android.app.Application; import android.app.Application;
import com.facebook.react.BuildConfig; import com.facebook.react.BuildConfig;
import com.facebook.react.ReactApplication; import com.facebook.react.ReactApplication;
import com.facebook.react.ReactNativeHost; import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage; import com.facebook.react.ReactPackage;
import com.facebook.react.shell.MainReactPackage; import com.facebook.react.shell.MainReactPackage;
import com.facebook.react.views.text.ReactFontManager; import com.facebook.react.views.text.ReactFontManager;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
public class RNTesterApplication extends Application implements ReactApplication { public class RNTesterApplication extends Application implements ReactApplication {
private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) { private final ReactNativeHost mReactNativeHost =
new ReactNativeHost(this) {
@Override @Override
public String getJSMainModuleName() { public String getJSMainModuleName() {
return "RNTester/js/RNTesterApp.android"; return "RNTester/js/RNTesterApp.android";
@ -39,9 +36,7 @@ public class RNTesterApplication extends Application implements ReactApplication
@Override @Override
public List<ReactPackage> getPackages() { public List<ReactPackage> getPackages() {
return Arrays.<ReactPackage>asList( return Arrays.<ReactPackage>asList(new MainReactPackage());
new MainReactPackage()
);
} }
}; };

Просмотреть файл

@ -1,25 +1,21 @@
/** /**
* Copyright (c) Facebook, Inc. and its affiliates. * Copyright (c) Facebook, Inc. and its affiliates.
* *
* This source code is licensed under the MIT license found in the * <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* LICENSE file in the root directory of this source tree. * directory of this source tree.
*/ */
package com.facebook.react.testing; package com.facebook.react.testing;
import com.facebook.react.bridge.BaseJavaModule;
import com.facebook.react.bridge.JavaScriptModule;
import com.facebook.react.bridge.ReactMethod;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.concurrent.Semaphore; import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import com.facebook.react.bridge.BaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.JavaScriptModule;
import com.facebook.react.testing.ReactInstanceSpecForTest;
import com.facebook.react.testing.ReactAppInstrumentationTestCase;
/** /**
* Shared by {@link ReactScrollViewTestCase} and {@link ReactHorizontalScrollViewTestCase}. * Shared by {@link ReactScrollViewTestCase} and {@link ReactHorizontalScrollViewTestCase}. See also
* See also ScrollViewTestModule.js * ScrollViewTestModule.js
*/ */
public abstract class AbstractScrollViewTestCase extends ReactAppInstrumentationTestCase { public abstract class AbstractScrollViewTestCase extends ReactAppInstrumentationTestCase {
@ -38,8 +34,7 @@ public abstract class AbstractScrollViewTestCase extends ReactAppInstrumentation
@Override @Override
protected ReactInstanceSpecForTest createReactInstanceSpecForTest() { protected ReactInstanceSpecForTest createReactInstanceSpecForTest() {
mScrollListenerModule = new ScrollListenerModule(); mScrollListenerModule = new ScrollListenerModule();
return super.createReactInstanceSpecForTest() return super.createReactInstanceSpecForTest().addNativeModule(mScrollListenerModule);
.addNativeModule(mScrollListenerModule);
} }
// See ScrollViewListenerModule.js // See ScrollViewListenerModule.js

Просмотреть файл

@ -1,23 +1,19 @@
/** /**
* Copyright (c) Facebook, Inc. and its affiliates. * Copyright (c) Facebook, Inc. and its affiliates.
* *
* This source code is licensed under the MIT license found in the * <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* LICENSE file in the root directory of this source tree. * directory of this source tree.
*/ */
package com.facebook.react.testing; package com.facebook.react.testing;
import javax.annotation.Nullable;
import com.facebook.react.bridge.BaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import static junit.framework.Assert.assertFalse; import static junit.framework.Assert.assertFalse;
import static junit.framework.Assert.assertTrue; import static junit.framework.Assert.assertTrue;
/** import com.facebook.react.bridge.BaseJavaModule;
* NativeModule for tests that allows assertions from JS to propagate to Java. import com.facebook.react.bridge.ReactMethod;
*/ import javax.annotation.Nullable;
/** NativeModule for tests that allows assertions from JS to propagate to Java. */
public class AssertModule extends BaseJavaModule { public class AssertModule extends BaseJavaModule {
private boolean mGotSuccess; private boolean mGotSuccess;

Просмотреть файл

@ -1,10 +1,9 @@
/** /**
* Copyright (c) Facebook, Inc. and its affiliates. * Copyright (c) Facebook, Inc. and its affiliates.
* *
* This source code is licensed under the MIT license found in the * <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* LICENSE file in the root directory of this source tree. * directory of this source tree.
*/ */
package com.facebook.react.testing; package com.facebook.react.testing;
import com.facebook.react.bridge.Arguments; import com.facebook.react.bridge.Arguments;
@ -14,12 +13,11 @@ import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.ReadableArray; import com.facebook.react.bridge.ReadableArray;
import com.facebook.react.bridge.WritableMap; import com.facebook.react.bridge.WritableMap;
/** /** Dummy implementation of storage module, used for testing */
* Dummy implementation of storage module, used for testing
*/
public final class FakeAsyncLocalStorage extends BaseJavaModule { public final class FakeAsyncLocalStorage extends BaseJavaModule {
private static WritableMap errorMessage; private static WritableMap errorMessage;
static { static {
errorMessage = Arguments.createMap(); errorMessage = Arguments.createMap();
errorMessage.putString("message", "Fake Async Local Storage"); errorMessage.putString("message", "Fake Async Local Storage");

Просмотреть файл

@ -1,22 +1,18 @@
/** /**
* Copyright (c) Facebook, Inc. and its affiliates. * Copyright (c) Facebook, Inc. and its affiliates.
* *
* This source code is licensed under the MIT license found in the * <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* LICENSE file in the root directory of this source tree. * directory of this source tree.
*/ */
package com.facebook.react.testing; package com.facebook.react.testing;
import javax.annotation.Nullable;
import com.facebook.react.bridge.BaseJavaModule; import com.facebook.react.bridge.BaseJavaModule;
import com.facebook.react.bridge.ReactMethod; import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.ReadableArray; import com.facebook.react.bridge.ReadableArray;
import com.facebook.react.bridge.ReadableMap; import com.facebook.react.bridge.ReadableMap;
import javax.annotation.Nullable;
/** /** Dummy implementation of storage module, used for testing */
* Dummy implementation of storage module, used for testing
*/
public final class FakeWebSocketModule extends BaseJavaModule { public final class FakeWebSocketModule extends BaseJavaModule {
@Override @Override
@ -34,18 +30,14 @@ public final class FakeWebSocketModule extends BaseJavaModule {
final String url, final String url,
@Nullable final ReadableArray protocols, @Nullable final ReadableArray protocols,
@Nullable final ReadableMap headers, @Nullable final ReadableMap headers,
final int id) { final int id) {}
}
@ReactMethod @ReactMethod
public void close(int code, String reason, int id) { public void close(int code, String reason, int id) {}
}
@ReactMethod @ReactMethod
public void send(String message, int id) { public void send(String message, int id) {}
}
@ReactMethod @ReactMethod
public void sendBinary(String base64String, int id) { public void sendBinary(String base64String, int id) {}
}
} }

Просмотреть файл

@ -1,21 +1,16 @@
/** /**
* Copyright (c) Facebook, Inc. and its affiliates. * Copyright (c) Facebook, Inc. and its affiliates.
* *
* This source code is licensed under the MIT license found in the * <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* LICENSE file in the root directory of this source tree. * directory of this source tree.
*/ */
package com.facebook.react.testing; package com.facebook.react.testing;
import java.util.List; import com.facebook.react.ReactPackage;
import android.view.View;
import com.facebook.react.bridge.NativeModule; import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.JavaScriptModule;
import com.facebook.react.uimanager.ViewManager; import com.facebook.react.uimanager.ViewManager;
import com.facebook.react.ReactPackage; import java.util.List;
/** /**
* This class wraps {@class ReactInstanceSpecForTest} in {@class ReactPackage} interface. * This class wraps {@class ReactInstanceSpecForTest} in {@class ReactPackage} interface.

Просмотреть файл

@ -1,23 +1,21 @@
/** /**
* Copyright (c) Facebook, Inc. and its affiliates. * Copyright (c) Facebook, Inc. and its affiliates.
* *
* This source code is licensed under the MIT license found in the * <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* LICENSE file in the root directory of this source tree. * directory of this source tree.
*/ */
package com.facebook.react.testing; package com.facebook.react.testing;
import com.facebook.react.bridge.BaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.concurrent.CountDownLatch; import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import com.facebook.react.bridge.BaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
/** /**
* Native module provides single method {@link #record} which records its single int argument * Native module provides single method {@link #record} which records its single int argument in
* in calls array * calls array
*/ */
public class IntRecordingModule extends BaseJavaModule { public class IntRecordingModule extends BaseJavaModule {

Просмотреть файл

@ -1,26 +1,23 @@
/** /**
* Copyright (c) Facebook, Inc. and its affiliates. * Copyright (c) Facebook, Inc. and its affiliates.
* *
* This source code is licensed under the MIT license found in the * <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* LICENSE file in the root directory of this source tree. * directory of this source tree.
*/ */
package com.facebook.react.testing; package com.facebook.react.testing;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import com.facebook.react.bridge.BaseJavaModule; import com.facebook.react.bridge.BaseJavaModule;
import com.facebook.react.bridge.Callback; import com.facebook.react.bridge.Callback;
import com.facebook.react.bridge.ReactMethod; import com.facebook.react.bridge.ReactMethod;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
/** /**
* This class is used to verify that some JS integration tests have completed successfully. * This class is used to verify that some JS integration tests have completed successfully. The JS
* The JS integration tests can be started from a ReactIntegrationTestCase and upon * integration tests can be started from a ReactIntegrationTestCase and upon finishing successfully
* finishing successfully the {@link JSIntegrationTestChecker#testDone()} method will be called. * the {@link JSIntegrationTestChecker#testDone()} method will be called. To verify if the test has
* To verify if the test has completed successfully, call {#link JSIntegrationTestChecker#await()} * completed successfully, call {#link JSIntegrationTestChecker#await()} to wait for the test to
* to wait for the test to run, and {#link JSIntegrationTestChecker#isTestDone()} to check if it * run, and {#link JSIntegrationTestChecker#isTestDone()} to check if it completed successfully.
* completed successfully.
*/ */
public class JSIntegrationTestChecker extends BaseJavaModule { public class JSIntegrationTestChecker extends BaseJavaModule {
@ -41,8 +38,7 @@ public class JSIntegrationTestChecker extends BaseJavaModule {
} }
@ReactMethod @ReactMethod
public void verifySnapshot(Callback callback) { public void verifySnapshot(Callback callback) {}
}
public boolean await(long ms) { public boolean await(long ms) {
try { try {

Просмотреть файл

@ -1,10 +1,9 @@
/** /**
* Copyright (c) Facebook, Inc. and its affiliates. * Copyright (c) Facebook, Inc. and its affiliates.
* *
* This source code is licensed under the MIT license found in the * <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* LICENSE file in the root directory of this source tree. * directory of this source tree.
*/ */
package com.facebook.react.testing; package com.facebook.react.testing;
import java.io.PrintWriter; import java.io.PrintWriter;

Просмотреть файл

@ -1,10 +1,9 @@
/** /**
* Copyright (c) Facebook, Inc. and its affiliates. * Copyright (c) Facebook, Inc. and its affiliates.
* *
* This source code is licensed under the MIT license found in the * <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* LICENSE file in the root directory of this source tree. * directory of this source tree.
*/ */
package com.facebook.react.testing; package com.facebook.react.testing;
import android.content.Intent; import android.content.Intent;
@ -19,11 +18,9 @@ import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import javax.annotation.Nullable; import javax.annotation.Nullable;
/** /** Base class for instrumentation tests that runs React based react application in UI mode */
* Base class for instrumentation tests that runs React based react application in UI mode public abstract class ReactAppInstrumentationTestCase
*/ extends ActivityInstrumentationTestCase2<ReactAppTestActivity> implements IdleWaiter {
public abstract class ReactAppInstrumentationTestCase extends
ActivityInstrumentationTestCase2<ReactAppTestActivity> implements IdleWaiter {
public ReactAppInstrumentationTestCase() { public ReactAppInstrumentationTestCase() {
super(ReactAppTestActivity.class); super(ReactAppTestActivity.class);
@ -38,9 +35,7 @@ public abstract class ReactAppInstrumentationTestCase extends
setActivityIntent(intent); setActivityIntent(intent);
final ReactAppTestActivity activity = getActivity(); final ReactAppTestActivity activity = getActivity();
activity.loadApp( activity.loadApp(
getReactApplicationKeyUnderTest(), getReactApplicationKeyUnderTest(), createReactInstanceSpecForTest(), getEnableDevSupport());
createReactInstanceSpecForTest(),
getEnableDevSupport());
waitForBridgeAndUIIdle(); waitForBridgeAndUIIdle();
} }
@ -56,8 +51,8 @@ public abstract class ReactAppInstrumentationTestCase extends
} }
/** /**
* This method isn't safe since it doesn't factor in layout-only view removal. Use * This method isn't safe since it doesn't factor in layout-only view removal. Use {@link
* {@link #getViewByTestId(String)} instead. * #getViewByTestId(String)} instead.
*/ */
@Deprecated @Deprecated
public <T extends View> T getViewAtPath(int... path) { public <T extends View> T getViewAtPath(int... path) {
@ -65,8 +60,8 @@ public abstract class ReactAppInstrumentationTestCase extends
} }
public <T extends View> T getViewByTestId(String testID) { public <T extends View> T getViewByTestId(String testID) {
return (T) ReactTestHelper return (T)
.getViewWithReactTestId((ViewGroup) getRootView().getParent(), testID); ReactTestHelper.getViewWithReactTestId((ViewGroup) getRootView().getParent(), testID);
} }
public SingleTouchGestureGenerator createGestureGenerator() { public SingleTouchGestureGenerator createGestureGenerator() {
@ -87,7 +82,8 @@ public abstract class ReactAppInstrumentationTestCase extends
final CountDownLatch latch = new CountDownLatch(1); final CountDownLatch latch = new CountDownLatch(1);
final BitmapHolder bitmapHolder = new BitmapHolder(); final BitmapHolder bitmapHolder = new BitmapHolder();
final Runnable getScreenshotRunnable = new Runnable() { final Runnable getScreenshotRunnable =
new Runnable() {
private static final int MAX_TRIES = 1000; private static final int MAX_TRIES = 1000;
// This is the constant used in the support library for APIs that don't have Choreographer // This is the constant used in the support library for APIs that don't have Choreographer
@ -125,8 +121,8 @@ public abstract class ReactAppInstrumentationTestCase extends
} }
/** /**
* Implement this method to provide application key to be launched. List of available * Implement this method to provide application key to be launched. List of available application
* application is located in TestBundle.js file * is located in TestBundle.js file
*/ */
protected abstract String getReactApplicationKeyUnderTest(); protected abstract String getReactApplicationKeyUnderTest();
@ -138,9 +134,7 @@ public abstract class ReactAppInstrumentationTestCase extends
return false; return false;
} }
/** /** Override this method to provide extra native modules to be loaded before the app starts */
* Override this method to provide extra native modules to be loaded before the app starts
*/
protected ReactInstanceSpecForTest createReactInstanceSpecForTest() { protected ReactInstanceSpecForTest createReactInstanceSpecForTest() {
return new ReactInstanceSpecForTest(); return new ReactInstanceSpecForTest();
} }
@ -149,9 +143,7 @@ public abstract class ReactAppInstrumentationTestCase extends
return getActivity().getReactContext(); return getActivity().getReactContext();
} }
/** /** Helper class to pass the bitmap between execution scopes in {@link #getScreenshot()}. */
* Helper class to pass the bitmap between execution scopes in {@link #getScreenshot()}.
*/
private static class BitmapHolder { private static class BitmapHolder {
public @Nullable volatile Bitmap bitmap; public @Nullable volatile Bitmap bitmap;

Просмотреть файл

@ -11,15 +11,14 @@ import static com.facebook.react.bridge.UiThreadUtil.runOnUiThread;
import android.content.Intent; import android.content.Intent;
import android.graphics.Bitmap; import android.graphics.Bitmap;
import android.os.Bundle; import android.os.Bundle;
import androidx.fragment.app.FragmentActivity;
import android.view.View; import android.view.View;
import android.view.ViewTreeObserver; import android.view.ViewTreeObserver;
import android.widget.FrameLayout; import android.widget.FrameLayout;
import androidx.fragment.app.FragmentActivity;
import com.facebook.infer.annotation.Assertions; import com.facebook.infer.annotation.Assertions;
import com.facebook.react.ReactInstanceManager; import com.facebook.react.ReactInstanceManager;
import com.facebook.react.ReactInstanceManagerBuilder; import com.facebook.react.ReactInstanceManagerBuilder;
import com.facebook.react.ReactRootView; import com.facebook.react.ReactRootView;
import com.facebook.react.bridge.JSIModule;
import com.facebook.react.bridge.JSIModulePackage; import com.facebook.react.bridge.JSIModulePackage;
import com.facebook.react.bridge.JSIModuleProvider; import com.facebook.react.bridge.JSIModuleProvider;
import com.facebook.react.bridge.JSIModuleSpec; import com.facebook.react.bridge.JSIModuleSpec;
@ -35,17 +34,13 @@ import com.facebook.react.modules.core.PermissionListener;
import com.facebook.react.shell.MainReactPackage; import com.facebook.react.shell.MainReactPackage;
import com.facebook.react.testing.idledetection.ReactBridgeIdleSignaler; import com.facebook.react.testing.idledetection.ReactBridgeIdleSignaler;
import com.facebook.react.testing.idledetection.ReactIdleDetectionUtil; import com.facebook.react.testing.idledetection.ReactIdleDetectionUtil;
import com.facebook.react.uimanager.UIManagerModule;
import com.facebook.react.uimanager.ViewManager;
import com.facebook.react.uimanager.ViewManagerRegistry; import com.facebook.react.uimanager.ViewManagerRegistry;
import com.facebook.react.uimanager.events.EventDispatcher;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
import java.util.concurrent.CountDownLatch; import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import javax.annotation.Nullable; import javax.annotation.Nullable;
public class ReactAppTestActivity extends FragmentActivity public class ReactAppTestActivity extends FragmentActivity
implements DefaultHardwareBackBtnHandler, PermissionAwareActivity { implements DefaultHardwareBackBtnHandler, PermissionAwareActivity {
@ -194,10 +189,12 @@ public class ReactAppTestActivity extends FragmentActivity
waitForBridgeAndUIIdle(); waitForBridgeAndUIIdle();
waitForLayout(5000); waitForLayout(5000);
} catch (InterruptedException e) { } catch (InterruptedException e) {
throw new RuntimeException("Layout never occurred for component " + appKey, e);} throw new RuntimeException("Layout never occurred for component " + appKey, e);
}
} }
public void loadBundle(final ReactInstanceSpecForTest spec, String bundleName, boolean useDevSupport) { public void loadBundle(
final ReactInstanceSpecForTest spec, String bundleName, boolean useDevSupport) {
mBridgeIdleSignaler = new ReactBridgeIdleSignaler(); mBridgeIdleSignaler = new ReactBridgeIdleSignaler();
@ -215,11 +212,11 @@ public class ReactAppTestActivity extends FragmentActivity
builder.addPackage(new MainReactPackage()); builder.addPackage(new MainReactPackage());
} }
/** /**
* The {@link ReactContext#mCurrentActivity} never to be set if initial lifecycle state is resumed. * The {@link ReactContext#mCurrentActivity} never to be set if initial lifecycle state is
* So we should call {@link ReactInstanceManagerBuilder#setCurrentActivity}. * resumed. So we should call {@link ReactInstanceManagerBuilder#setCurrentActivity}.
* *
* Finally,{@link ReactInstanceManagerBuilder#build()} will create instance of {@link ReactInstanceManager}. * <p>Finally,{@link ReactInstanceManagerBuilder#build()} will create instance of {@link
* And also will set {@link ReactContext#mCurrentActivity}. * ReactInstanceManager}. And also will set {@link ReactContext#mCurrentActivity}.
*/ */
builder.setCurrentActivity(this); builder.setCurrentActivity(this);
builder builder
@ -251,10 +248,14 @@ public class ReactAppTestActivity extends FragmentActivity
public UIManager get() { public UIManager get() {
ViewManagerRegistry viewManagerRegistry = ViewManagerRegistry viewManagerRegistry =
new ViewManagerRegistry( new ViewManagerRegistry(
mReactInstanceManager.getOrCreateViewManagers(reactApplicationContext)); mReactInstanceManager.getOrCreateViewManagers(
reactApplicationContext));
FabricUIManagerFactory factory = spec.getFabricUIManagerFactory(); FabricUIManagerFactory factory = spec.getFabricUIManagerFactory();
return factory != null ? factory.getFabricUIManager(reactApplicationContext, viewManagerRegistry, jsContext) : null; return factory != null
? factory.getFabricUIManager(
reactApplicationContext, viewManagerRegistry, jsContext)
: null;
} }
}; };
} }

Просмотреть файл

@ -53,7 +53,8 @@ public class ReactInstanceSpecForTest {
return this; return this;
} }
public ReactInstanceSpecForTest setFabricUIManagerFactory(@Nullable FabricUIManagerFactory fabricUIManagerFactory) { public ReactInstanceSpecForTest setFabricUIManagerFactory(
@Nullable FabricUIManagerFactory fabricUIManagerFactory) {
mFabricUIManagerFactory = fabricUIManagerFactory; mFabricUIManagerFactory = fabricUIManagerFactory;
return this; return this;
} }

Просмотреть файл

@ -1,24 +1,16 @@
/** /**
* Copyright (c) Facebook, Inc. and its affiliates. * Copyright (c) Facebook, Inc. and its affiliates.
* *
* This source code is licensed under the MIT license found in the * <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* LICENSE file in the root directory of this source tree. * directory of this source tree.
*/ */
package com.facebook.react.testing; package com.facebook.react.testing;
import com.facebook.react.modules.core.ReactChoreographer; import static org.mockito.Mockito.mock;
import javax.annotation.Nullable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import android.app.Application;
import android.test.AndroidTestCase; import android.test.AndroidTestCase;
import android.view.View; import android.view.View;
import android.view.ViewGroup; import android.view.ViewGroup;
import com.facebook.infer.annotation.Assertions; import com.facebook.infer.annotation.Assertions;
import com.facebook.react.bridge.BaseJavaModule; import com.facebook.react.bridge.BaseJavaModule;
import com.facebook.react.bridge.CatalystInstance; import com.facebook.react.bridge.CatalystInstance;
@ -29,26 +21,27 @@ import com.facebook.react.bridge.SoftAssertions;
import com.facebook.react.bridge.UiThreadUtil; import com.facebook.react.bridge.UiThreadUtil;
import com.facebook.react.common.futures.SimpleSettableFuture; import com.facebook.react.common.futures.SimpleSettableFuture;
import com.facebook.react.devsupport.interfaces.DevSupportManager; import com.facebook.react.devsupport.interfaces.DevSupportManager;
import com.facebook.react.modules.core.ReactChoreographer;
import com.facebook.react.modules.core.Timing; import com.facebook.react.modules.core.Timing;
import com.facebook.react.testing.idledetection.ReactBridgeIdleSignaler; import com.facebook.react.testing.idledetection.ReactBridgeIdleSignaler;
import com.facebook.react.testing.idledetection.ReactIdleDetectionUtil; import com.facebook.react.testing.idledetection.ReactIdleDetectionUtil;
import com.facebook.soloader.SoLoader; import com.facebook.soloader.SoLoader;
import java.util.concurrent.CountDownLatch;
import static org.mockito.Mockito.mock; import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import javax.annotation.Nullable;
/** /**
* Use this class for writing integration tests of catalyst. This class will run all JNI call * Use this class for writing integration tests of catalyst. This class will run all JNI call within
* within separate android looper, thus you don't need to care about starting your own looper. * separate android looper, thus you don't need to care about starting your own looper.
* *
* Keep in mind that all JS remote method calls and script load calls are asynchronous and you * <p>Keep in mind that all JS remote method calls and script load calls are asynchronous and you
* should not expect them to return results immediately. * should not expect them to return results immediately.
* *
* In order to write catalyst integration: * <p>In order to write catalyst integration: 1) Make {@link ReactIntegrationTestCase} a base class
* 1) Make {@link ReactIntegrationTestCase} a base class of your test case * of your test case 2) Use {@link ReactTestHelper#catalystInstanceBuilder()} instead of {@link
* 2) Use {@link ReactTestHelper#catalystInstanceBuilder()} * com.facebook.react.bridge.CatalystInstanceImpl.Builder} to build catalyst instance for testing
* instead of {@link com.facebook.react.bridge.CatalystInstanceImpl.Builder} to build catalyst * purposes
* instance for testing purposes
*
*/ */
public abstract class ReactIntegrationTestCase extends AndroidTestCase { public abstract class ReactIntegrationTestCase extends AndroidTestCase {
@ -76,7 +69,8 @@ public abstract class ReactIntegrationTestCase extends AndroidTestCase {
mInstance = null; mInstance = null;
final SimpleSettableFuture<Void> semaphore = new SimpleSettableFuture<>(); final SimpleSettableFuture<Void> semaphore = new SimpleSettableFuture<>();
UiThreadUtil.runOnUiThread(new Runnable() { UiThreadUtil.runOnUiThread(
new Runnable() {
@Override @Override
public void run() { public void run() {
if (contextToDestroy != null) { if (contextToDestroy != null) {
@ -90,8 +84,8 @@ public abstract class ReactIntegrationTestCase extends AndroidTestCase {
} }
/** /**
* This method isn't safe since it doesn't factor in layout-only view removal. Use * This method isn't safe since it doesn't factor in layout-only view removal. Use {@link
* {@link #getViewByTestId} instead. * #getViewByTestId} instead.
*/ */
@Deprecated @Deprecated
public <T extends View> T getViewAtPath(ViewGroup rootView, int... path) { public <T extends View> T getViewAtPath(ViewGroup rootView, int... path) {
@ -170,9 +164,7 @@ public abstract class ReactIntegrationTestCase extends AndroidTestCase {
public void waitForBridgeAndUIIdle() { public void waitForBridgeAndUIIdle() {
ReactIdleDetectionUtil.waitForBridgeAndUIIdle( ReactIdleDetectionUtil.waitForBridgeAndUIIdle(
Assertions.assertNotNull(mBridgeIdleSignaler), Assertions.assertNotNull(mBridgeIdleSignaler), getContext(), IDLE_TIMEOUT_MS);
getContext(),
IDLE_TIMEOUT_MS);
} }
@Override @Override

Просмотреть файл

@ -1,10 +1,9 @@
/** /**
* Copyright (c) Facebook, Inc. and its affiliates. * Copyright (c) Facebook, Inc. and its affiliates.
* *
* This source code is licensed under the MIT license found in the * <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* LICENSE file in the root directory of this source tree. * directory of this source tree.
*/ */
package com.facebook.react.testing; package com.facebook.react.testing;
import com.facebook.react.modules.debug.interfaces.DeveloperSettings; import com.facebook.react.modules.debug.interfaces.DeveloperSettings;
@ -47,7 +46,5 @@ public class ReactSettingsForTests implements DeveloperSettings {
} }
@Override @Override
public void setRemoteJSDebugEnabled(boolean remoteJSDebugEnabled) { public void setRemoteJSDebugEnabled(boolean remoteJSDebugEnabled) {}
}
} }

Просмотреть файл

@ -1,10 +1,9 @@
/** /**
* Copyright (c) Facebook, Inc. and its affiliates. * Copyright (c) Facebook, Inc. and its affiliates.
* *
* This source code is licensed under the MIT license found in the * <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* LICENSE file in the root directory of this source tree. * directory of this source tree.
*/ */
package com.facebook.react.testing; package com.facebook.react.testing;
import com.facebook.buck.android.support.exopackage.ApplicationLike; import com.facebook.buck.android.support.exopackage.ApplicationLike;
@ -15,9 +14,9 @@ import com.facebook.soloader.SoLoader;
/** /**
* Application class for the Catalyst Launcher to allow it to work as an exopackage. * Application class for the Catalyst Launcher to allow it to work as an exopackage.
* *
* Any app-specific code that should run before secondary dex files are loaded * <p>Any app-specific code that should run before secondary dex files are loaded (like setting up
* (like setting up crash reporting) should go in onBaseContextAttached. * crash reporting) should go in onBaseContextAttached. Anything that should run after secondary dex
* Anything that should run after secondary dex should go in CatalystApplicationImpl.onCreate. * should go in CatalystApplicationImpl.onCreate.
*/ */
public class ReactTestAppShell extends ExopackageApplication<ApplicationLike> { public class ReactTestAppShell extends ExopackageApplication<ApplicationLike> {

Просмотреть файл

@ -1,14 +1,12 @@
/** /**
* Copyright (c) Facebook, Inc. and its affiliates. * Copyright (c) Facebook, Inc. and its affiliates.
* *
* This source code is licensed under the MIT license found in the * <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* LICENSE file in the root directory of this source tree. * directory of this source tree.
*/ */
package com.facebook.react.testing; package com.facebook.react.testing;
import android.app.Application; import android.app.Application;
import com.facebook.buck.android.support.exopackage.DefaultApplicationLike; import com.facebook.buck.android.support.exopackage.DefaultApplicationLike;
public class ReactTestApplicationImpl extends DefaultApplicationLike { public class ReactTestApplicationImpl extends DefaultApplicationLike {

Просмотреть файл

@ -1,14 +1,12 @@
/** /**
* Copyright (c) Facebook, Inc. and its affiliates. * Copyright (c) Facebook, Inc. and its affiliates.
* *
* This source code is licensed under the MIT license found in the * <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* LICENSE file in the root directory of this source tree. * directory of this source tree.
*/ */
package com.facebook.react.testing; package com.facebook.react.testing;
import android.content.Context; import android.content.Context;
import com.facebook.react.ReactInstanceManagerBuilder; import com.facebook.react.ReactInstanceManagerBuilder;
import com.facebook.react.bridge.CatalystInstance; import com.facebook.react.bridge.CatalystInstance;
import com.facebook.react.bridge.NativeModule; import com.facebook.react.bridge.NativeModule;
@ -16,10 +14,13 @@ import com.facebook.react.bridge.NativeModule;
public interface ReactTestFactory { public interface ReactTestFactory {
interface ReactInstanceEasyBuilder { interface ReactInstanceEasyBuilder {
ReactInstanceEasyBuilder setContext(Context context); ReactInstanceEasyBuilder setContext(Context context);
ReactInstanceEasyBuilder addNativeModule(NativeModule module); ReactInstanceEasyBuilder addNativeModule(NativeModule module);
CatalystInstance build(); CatalystInstance build();
} }
ReactInstanceEasyBuilder getCatalystInstanceBuilder(); ReactInstanceEasyBuilder getCatalystInstanceBuilder();
ReactInstanceManagerBuilder getReactInstanceManagerBuilder(); ReactInstanceManagerBuilder getReactInstanceManagerBuilder();
} }

Просмотреть файл

@ -1,23 +1,15 @@
/** /**
* Copyright (c) Facebook, Inc. and its affiliates. * Copyright (c) Facebook, Inc. and its affiliates.
* *
* This source code is licensed under the MIT license found in the * <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* LICENSE file in the root directory of this source tree. * directory of this source tree.
*/ */
package com.facebook.react.testing; package com.facebook.react.testing;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import javax.annotation.Nullable;
import android.app.Instrumentation;
import android.content.Context; import android.content.Context;
import android.view.View; import android.view.View;
import android.view.ViewGroup; import android.view.ViewGroup;
import com.android.internal.util.Predicate;
import com.facebook.infer.annotation.Assertions; import com.facebook.infer.annotation.Assertions;
import com.facebook.react.NativeModuleRegistryBuilder; import com.facebook.react.NativeModuleRegistryBuilder;
import com.facebook.react.R; import com.facebook.react.R;
@ -25,19 +17,20 @@ import com.facebook.react.ReactInstanceManager;
import com.facebook.react.ReactInstanceManagerBuilder; import com.facebook.react.ReactInstanceManagerBuilder;
import com.facebook.react.ReactPackage; import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.CatalystInstance; import com.facebook.react.bridge.CatalystInstance;
import com.facebook.react.bridge.JavaScriptModuleRegistry;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.NativeModuleCallExceptionHandler;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.WritableNativeMap;
import com.facebook.react.bridge.queue.ReactQueueConfigurationSpec;
import com.facebook.react.bridge.CatalystInstanceImpl; import com.facebook.react.bridge.CatalystInstanceImpl;
import com.facebook.react.bridge.JSBundleLoader; import com.facebook.react.bridge.JSBundleLoader;
import com.facebook.react.bridge.JavaScriptExecutor; import com.facebook.react.bridge.JavaScriptExecutor;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.NativeModuleCallExceptionHandler;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.queue.ReactQueueConfigurationSpec;
import com.facebook.react.jscexecutor.JSCExecutorFactory; import com.facebook.react.jscexecutor.JSCExecutorFactory;
import com.facebook.react.modules.core.ReactChoreographer; import com.facebook.react.modules.core.ReactChoreographer;
import com.facebook.react.uimanager.ViewManager; import com.facebook.react.uimanager.ViewManager;
import com.android.internal.util.Predicate; import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import javax.annotation.Nullable;
public class ReactTestHelper { public class ReactTestHelper {
private static class DefaultReactTestFactory implements ReactTestFactory { private static class DefaultReactTestFactory implements ReactTestFactory {
@ -56,12 +49,12 @@ public class ReactTestHelper {
@Override @Override
public ReactInstanceEasyBuilder addNativeModule(final NativeModule nativeModule) { public ReactInstanceEasyBuilder addNativeModule(final NativeModule nativeModule) {
if (mNativeModuleRegistryBuilder == null) { if (mNativeModuleRegistryBuilder == null) {
mNativeModuleRegistryBuilder = new NativeModuleRegistryBuilder( mNativeModuleRegistryBuilder =
(ReactApplicationContext) mContext, new NativeModuleRegistryBuilder((ReactApplicationContext) mContext, null);
null);
} }
Assertions.assertNotNull(nativeModule); Assertions.assertNotNull(nativeModule);
mNativeModuleRegistryBuilder.processPackage(new ReactPackage(){ mNativeModuleRegistryBuilder.processPackage(
new ReactPackage() {
@Override @Override
public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) { public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
return Collections.emptyList(); return Collections.emptyList();
@ -78,9 +71,8 @@ public class ReactTestHelper {
@Override @Override
public CatalystInstance build() { public CatalystInstance build() {
if (mNativeModuleRegistryBuilder == null) { if (mNativeModuleRegistryBuilder == null) {
mNativeModuleRegistryBuilder = new NativeModuleRegistryBuilder( mNativeModuleRegistryBuilder =
(ReactApplicationContext) mContext, new NativeModuleRegistryBuilder((ReactApplicationContext) mContext, null);
null);
} }
JavaScriptExecutor executor = null; JavaScriptExecutor executor = null;
try { try {
@ -92,10 +84,9 @@ public class ReactTestHelper {
.setReactQueueConfigurationSpec(ReactQueueConfigurationSpec.createDefault()) .setReactQueueConfigurationSpec(ReactQueueConfigurationSpec.createDefault())
.setJSExecutor(executor) .setJSExecutor(executor)
.setRegistry(mNativeModuleRegistryBuilder.build()) .setRegistry(mNativeModuleRegistryBuilder.build())
.setJSBundleLoader(JSBundleLoader.createAssetLoader( .setJSBundleLoader(
mContext, JSBundleLoader.createAssetLoader(
"assets://AndroidTestBundle.js", mContext, "assets://AndroidTestBundle.js", false /* Asynchronous */))
false/* Asynchronous */))
.setNativeModuleCallExceptionHandler( .setNativeModuleCallExceptionHandler(
new NativeModuleCallExceptionHandler() { new NativeModuleCallExceptionHandler() {
@Override @Override
@ -168,9 +159,7 @@ public class ReactTestHelper {
return postBuilder; return postBuilder;
} }
/** /** Gets the view at given path in the UI hierarchy, ignoring modals. */
* Gets the view at given path in the UI hierarchy, ignoring modals.
*/
public static <T extends View> T getViewAtPath(ViewGroup rootView, int... path) { public static <T extends View> T getViewAtPath(ViewGroup rootView, int... path) {
// The application root element is wrapped in a helper view in order // The application root element is wrapped in a helper view in order
// to be able to display modals. See renderApplication.js. // to be able to display modals. See renderApplication.js.

Просмотреть файл

@ -1,19 +1,17 @@
/** /**
* Copyright (c) Facebook, Inc. and its affiliates. * Copyright (c) Facebook, Inc. and its affiliates.
* *
* This source code is licensed under the MIT license found in the * <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* LICENSE file in the root directory of this source tree. * directory of this source tree.
*/ */
package com.facebook.react.testing; package com.facebook.react.testing;
import javax.annotation.Nullable;
import android.content.Context; import android.content.Context;
import android.graphics.Bitmap; import android.graphics.Bitmap;
import android.graphics.Canvas; import android.graphics.Canvas;
import android.os.Looper; import android.os.Looper;
import android.widget.FrameLayout; import android.widget.FrameLayout;
import javax.annotation.Nullable;
/** /**
* A FrameLayout that allows you to access the result of the last time its hierarchy was drawn. It * A FrameLayout that allows you to access the result of the last time its hierarchy was drawn. It
@ -35,8 +33,8 @@ public class ScreenshotingFrameLayout extends FrameLayout {
if (mBitmap == null) { if (mBitmap == null) {
mBitmap = createNewBitmap(canvas); mBitmap = createNewBitmap(canvas);
mCanvas.setBitmap(mBitmap); mCanvas.setBitmap(mBitmap);
} else if (mBitmap.getWidth() != canvas.getWidth() || } else if (mBitmap.getWidth() != canvas.getWidth()
mBitmap.getHeight() != canvas.getHeight()) { || mBitmap.getHeight() != canvas.getHeight()) {
mBitmap.recycle(); mBitmap.recycle();
mBitmap = createNewBitmap(canvas); mBitmap = createNewBitmap(canvas);
mCanvas.setBitmap(mBitmap); mCanvas.setBitmap(mBitmap);

Просмотреть файл

@ -1,28 +1,26 @@
/** /**
* Copyright (c) Facebook, Inc. and its affiliates. * Copyright (c) Facebook, Inc. and its affiliates.
* *
* This source code is licensed under the MIT license found in the * <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* LICENSE file in the root directory of this source tree. * directory of this source tree.
*/ */
package com.facebook.react.testing; package com.facebook.react.testing;
import android.os.SystemClock; import android.os.SystemClock;
import android.view.MotionEvent; import android.view.MotionEvent;
import android.view.View; import android.view.View;
import android.view.ViewConfiguration; import android.view.ViewConfiguration;
import com.facebook.react.testing.idledetection.IdleWaiter; import com.facebook.react.testing.idledetection.IdleWaiter;
/** /**
* Provides methods for generating touch events and dispatching them directly to a given view. * Provides methods for generating touch events and dispatching them directly to a given view.
* Events scenarios are based on {@link android.test.TouchUtils} but they get gets dispatched * Events scenarios are based on {@link android.test.TouchUtils} but they get gets dispatched
* directly through the view hierarchy using {@link View#dispatchTouchEvent} method instead of * directly through the view hierarchy using {@link View#dispatchTouchEvent} method instead of using
* using instrumentation API. * instrumentation API.
* <p> *
* All the events for a gesture are dispatched immediately which makes tests run very fast. * <p>All the events for a gesture are dispatched immediately which makes tests run very fast. The
* The eventTime for each event is still set correctly. Android's gesture recognizers check * eventTime for each event is still set correctly. Android's gesture recognizers check eventTime in
* eventTime in order to figure out gesture speed, and therefore scroll vs fling is recognized. * order to figure out gesture speed, and therefore scroll vs fling is recognized.
*/ */
public class SingleTouchGestureGenerator { public class SingleTouchGestureGenerator {
@ -44,10 +42,7 @@ public class SingleTouchGestureGenerator {
} }
private SingleTouchGestureGenerator dispatchEvent( private SingleTouchGestureGenerator dispatchEvent(
final int action, final int action, final float x, final float y, long eventTime) {
final float x,
final float y,
long eventTime) {
mEventTime = eventTime; mEventTime = eventTime;
if (action == MotionEvent.ACTION_DOWN) { if (action == MotionEvent.ACTION_DOWN) {
mLastDownTime = eventTime; mLastDownTime = eventTime;
@ -90,10 +85,7 @@ public class SingleTouchGestureGenerator {
} }
private SingleTouchGestureGenerator dispatchDelayedEvent( private SingleTouchGestureGenerator dispatchDelayedEvent(
int action, int action, float x, float y, long delay) {
float x,
float y,
long delay) {
return dispatchEvent(action, x, y, mEventTime + delay); return dispatchEvent(action, x, y, mEventTime + delay);
} }
@ -127,12 +119,7 @@ public class SingleTouchGestureGenerator {
} }
public SingleTouchGestureGenerator drag( public SingleTouchGestureGenerator drag(
float fromX, float fromX, float fromY, float toX, float toY, int stepCount, long totalDelay) {
float fromY,
float toX,
float toY,
int stepCount,
long totalDelay) {
float xStep = (toX - fromX) / stepCount; float xStep = (toX - fromX) / stepCount;
float yStep = (toY - fromY) / stepCount; float yStep = (toY - fromY) / stepCount;

Просмотреть файл

@ -1,21 +1,19 @@
/** /**
* Copyright (c) Facebook, Inc. and its affiliates. * Copyright (c) Facebook, Inc. and its affiliates.
* *
* This source code is licensed under the MIT license found in the * <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* LICENSE file in the root directory of this source tree. * directory of this source tree.
*/ */
package com.facebook.react.testing; package com.facebook.react.testing;
import java.util.ArrayList;
import java.util.List;
import com.facebook.react.bridge.BaseJavaModule; import com.facebook.react.bridge.BaseJavaModule;
import com.facebook.react.bridge.ReactMethod; import com.facebook.react.bridge.ReactMethod;
import java.util.ArrayList;
import java.util.List;
/** /**
* Native module provides single method {@link #record} which records its single string argument * Native module provides single method {@link #record} which records its single string argument in
* in calls array * calls array
*/ */
public class StringRecordingModule extends BaseJavaModule { public class StringRecordingModule extends BaseJavaModule {

Просмотреть файл

@ -1,15 +1,12 @@
/** /**
* Copyright (c) Facebook, Inc. and its affiliates. * Copyright (c) Facebook, Inc. and its affiliates.
* *
* This source code is licensed under the MIT license found in the * <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* LICENSE file in the root directory of this source tree. * directory of this source tree.
*/ */
package com.facebook.react.testing.idledetection; package com.facebook.react.testing.idledetection;
/** /** Interface for something that knows how to wait for bridge and UI idle. */
* Interface for something that knows how to wait for bridge and UI idle.
*/
public interface IdleWaiter { public interface IdleWaiter {
void waitForBridgeAndUIIdle(); void waitForBridgeAndUIIdle();

Просмотреть файл

@ -1,17 +1,15 @@
/** /**
* Copyright (c) Facebook, Inc. and its affiliates. * Copyright (c) Facebook, Inc. and its affiliates.
* *
* This source code is licensed under the MIT license found in the * <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* LICENSE file in the root directory of this source tree. * directory of this source tree.
*/ */
package com.facebook.react.testing.idledetection; package com.facebook.react.testing.idledetection;
import com.facebook.react.bridge.NotThreadSafeBridgeIdleDebugListener;
import java.util.concurrent.Semaphore; import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import com.facebook.react.bridge.NotThreadSafeBridgeIdleDebugListener;
/** /**
* Utility class that uses {@link NotThreadSafeBridgeIdleDebugListener} interface to allow callers * Utility class that uses {@link NotThreadSafeBridgeIdleDebugListener} interface to allow callers
* to wait for the bridge to be idle. * to wait for the bridge to be idle.

Просмотреть файл

@ -1,10 +1,9 @@
/** /**
* Copyright (c) Facebook, Inc. and its affiliates. * Copyright (c) Facebook, Inc. and its affiliates.
* *
* This source code is licensed under the MIT license found in the * <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* LICENSE file in the root directory of this source tree. * directory of this source tree.
*/ */
package com.facebook.react.testing.idledetection; package com.facebook.react.testing.idledetection;
import com.facebook.react.bridge.ReactContext; import com.facebook.react.bridge.ReactContext;
@ -16,14 +15,12 @@ public class ReactIdleDetectionUtil {
* bridge to become idle, then waiting for the UI thread to become idle, then checking if the * bridge to become idle, then waiting for the UI thread to become idle, then checking if the
* bridge is idle again (if the bridge was idle before and is still idle after running the UI * bridge is idle again (if the bridge was idle before and is still idle after running the UI
* thread to idle, then there are no more events to process in either place). * thread to idle, then there are no more events to process in either place).
* <p/> *
* Also waits for any Choreographer callbacks to run after the initial sync since things like UI * <p>Also waits for any Choreographer callbacks to run after the initial sync since things like
* events are initiated from Choreographer callbacks. * UI events are initiated from Choreographer callbacks.
*/ */
public static void waitForBridgeAndUIIdle( public static void waitForBridgeAndUIIdle(
ReactBridgeIdleSignaler idleSignaler, ReactBridgeIdleSignaler idleSignaler, final ReactContext reactContext, long timeoutMs) {
final ReactContext reactContext,
long timeoutMs) {
return; return;
// TODO: re-enable after cleanup of android-x migration // TODO: re-enable after cleanup of android-x migration

Просмотреть файл

@ -1,14 +1,11 @@
/** /**
* Copyright (c) Facebook, Inc. and its affiliates. * Copyright (c) Facebook, Inc. and its affiliates.
* *
* This source code is licensed under the MIT license found in the * <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* LICENSE file in the root directory of this source tree. * directory of this source tree.
*/ */
package com.facebook.react.testing.network; package com.facebook.react.testing.network;
import javax.annotation.Nullable;
import com.facebook.react.bridge.Arguments; import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.Callback; import com.facebook.react.bridge.Callback;
import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReactApplicationContext;
@ -20,6 +17,7 @@ import com.facebook.react.bridge.WritableArray;
import com.facebook.react.bridge.WritableMap; import com.facebook.react.bridge.WritableMap;
import com.facebook.react.module.annotations.ReactModule; import com.facebook.react.module.annotations.ReactModule;
import com.facebook.react.modules.core.DeviceEventManagerModule; import com.facebook.react.modules.core.DeviceEventManagerModule;
import javax.annotation.Nullable;
/** /**
* Mock Networking module that records last request received by {@link #sendRequest} method and * Mock Networking module that records last request received by {@link #sendRequest} method and
@ -70,10 +68,7 @@ public class NetworkRecordingModuleMock extends ReactContextBaseJavaModule {
} }
private void fireReactCallback( private void fireReactCallback(
Callback callback, Callback callback, int status, @Nullable String headers, @Nullable String body) {
int status,
@Nullable String headers,
@Nullable String body) {
callback.invoke(status, headers, body); callback.invoke(status, headers, body);
} }

Просмотреть файл

@ -6,16 +6,14 @@
package com.facebook.react.testing.rule; package com.facebook.react.testing.rule;
import android.app.Activity; import android.app.Activity;
import android.os.Build;
import androidx.test.rule.ActivityTestRule;
import android.view.ViewTreeObserver.OnGlobalLayoutListener; import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import androidx.test.rule.ActivityTestRule;
import com.facebook.react.ReactInstanceManager; import com.facebook.react.ReactInstanceManager;
import com.facebook.react.ReactPackage; import com.facebook.react.ReactPackage;
import com.facebook.react.ReactRootView; import com.facebook.react.ReactRootView;
import com.facebook.react.bridge.ReactContext; import com.facebook.react.bridge.ReactContext;
import com.facebook.react.common.LifecycleState; import com.facebook.react.common.LifecycleState;
import com.facebook.react.shell.MainReactPackage; import com.facebook.react.shell.MainReactPackage;
import com.facebook.react.testing.ReactInstanceSpecForTest;
import com.facebook.react.testing.ReactTestHelper; import com.facebook.react.testing.ReactTestHelper;
import com.facebook.react.testing.idledetection.ReactBridgeIdleSignaler; import com.facebook.react.testing.idledetection.ReactBridgeIdleSignaler;
import com.facebook.react.testing.idledetection.ReactIdleDetectionUtil; import com.facebook.react.testing.idledetection.ReactIdleDetectionUtil;
@ -164,9 +162,7 @@ public class ReactNativeTestRule implements TestRule {
public void waitForIdleSync() { public void waitForIdleSync() {
ReactIdleDetectionUtil.waitForBridgeAndUIIdle( ReactIdleDetectionUtil.waitForBridgeAndUIIdle(
mBridgeIdleSignaler, mBridgeIdleSignaler, mReactInstanceManager.getCurrentReactContext(), IDLE_TIMEOUT_MS);
mReactInstanceManager.getCurrentReactContext(),
IDLE_TIMEOUT_MS);
} }
/** Returns the react view */ /** Returns the react view */

Просмотреть файл

@ -1,20 +1,16 @@
/** /**
* Copyright (c) 2013-present, Facebook, Inc. * Copyright (c) 2013-present, Facebook, Inc.
* *
* This source code is licensed under the MIT license found in the * <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* LICENSE file in the root directory of this source tree. * directory of this source tree.
*/ */
package com.facebook.react.tests; package com.facebook.react.tests;
import android.view.View; import android.view.View;
import com.facebook.react.testing.ReactInstanceSpecForTest;
import com.facebook.react.testing.StringRecordingModule;
import com.facebook.react.bridge.JavaScriptModule;
import com.facebook.react.testing.ReactAppInstrumentationTestCase; import com.facebook.react.testing.ReactAppInstrumentationTestCase;
import com.facebook.react.testing.ReactInstanceSpecForTest;
import com.facebook.react.testing.ReactTestHelper; import com.facebook.react.testing.ReactTestHelper;
import com.facebook.react.testing.StringRecordingModule;
/** /**
* Integration test for {@code removeClippedSubviews} property that verify correct scrollview * Integration test for {@code removeClippedSubviews} property that verify correct scrollview
@ -32,16 +28,14 @@ public class AnimatedTransformTest extends ReactAppInstrumentationTestCase {
@Override @Override
protected ReactInstanceSpecForTest createReactInstanceSpecForTest() { protected ReactInstanceSpecForTest createReactInstanceSpecForTest() {
mStringRecordingModule = new StringRecordingModule(); mStringRecordingModule = new StringRecordingModule();
return super.createReactInstanceSpecForTest() return super.createReactInstanceSpecForTest().addNativeModule(mStringRecordingModule);
.addNativeModule(mStringRecordingModule);
} }
public void testAnimatedRotation() { public void testAnimatedRotation() {
waitForBridgeAndUIIdle(); waitForBridgeAndUIIdle();
View button = ReactTestHelper.getViewWithReactTestId( View button =
getActivity().getRootView(), ReactTestHelper.getViewWithReactTestId(getActivity().getRootView(), "TouchableOpacity");
"TouchableOpacity");
// Tap the button which triggers the animated transform containing the // Tap the button which triggers the animated transform containing the
// rotation strings. // rotation strings.
@ -51,5 +45,4 @@ public class AnimatedTransformTest extends ReactAppInstrumentationTestCase {
// The previous cast error will prevent it from getting here // The previous cast error will prevent it from getting here
assertEquals(2, mStringRecordingModule.getCalls().size()); assertEquals(2, mStringRecordingModule.getCalls().size());
} }
} }

Просмотреть файл

@ -1,58 +1,54 @@
/** /**
* Copyright (c) Facebook, Inc. and its affiliates. * Copyright (c) Facebook, Inc. and its affiliates.
* *
* This source code is licensed under the MIT license found in the * <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* LICENSE file in the root directory of this source tree. * directory of this source tree.
*/ */
package com.facebook.react.tests; package com.facebook.react.tests;
import com.facebook.react.testing.ReactInstanceSpecForTest;
import com.facebook.react.bridge.JavaScriptModule; import com.facebook.react.bridge.JavaScriptModule;
import com.facebook.react.uimanager.UIManagerModule;
import com.facebook.react.testing.AssertModule; import com.facebook.react.testing.AssertModule;
import com.facebook.react.testing.ReactAppInstrumentationTestCase; import com.facebook.react.testing.ReactAppInstrumentationTestCase;
import com.facebook.react.testing.ReactInstanceSpecForTest;
import com.facebook.react.uimanager.UIManagerModule;
/** /**
* Tests for {@link UIManagerModule#measure}, {@link UIManagerModule#measureLayout}, and * Tests for {@link UIManagerModule#measure}, {@link UIManagerModule#measureLayout}, and {@link
* {@link UIManagerModule#measureLayoutRelativeToParent}. Tests measurement for views in the * UIManagerModule#measureLayoutRelativeToParent}. Tests measurement for views in the following
* following hierarchy: * hierarchy:
* *
* +---------------------------------------------+ * <p>+---------------------------------------------+ | A | | | | +-----------+ +---------+ | | | B
* | A | * | | D | | | | +---+ | | | | | | | C | | | | | | | | | | +---------+ | | | +---+ | | |
* | | * +-----------+ | | | | | | | +---------------------------------------------+
* | +-----------+ +---------+ |
* | | B | | D | |
* | | +---+ | | | |
* | | | C | | | | |
* | | | | | +---------+ |
* | | +---+ | |
* | +-----------+ |
* | |
* | |
* | |
* +---------------------------------------------+
* *
* View locations and dimensions: * <p>View locations and dimensions: A - (0,0) to (500, 500) (500x500) B - (50,80) to (250, 380)
* A - (0,0) to (500, 500) (500x500) * (200x300) C - (150,150) to (200, 300) (50x150) D - (400,100) to (450, 300) (50x200)
* B - (50,80) to (250, 380) (200x300)
* C - (150,150) to (200, 300) (50x150)
* D - (400,100) to (450, 300) (50x200)
*/ */
public class CatalystMeasureLayoutTest extends ReactAppInstrumentationTestCase { public class CatalystMeasureLayoutTest extends ReactAppInstrumentationTestCase {
private static interface MeasureLayoutTestModule extends JavaScriptModule { private static interface MeasureLayoutTestModule extends JavaScriptModule {
public void verifyMeasureOnViewA(); public void verifyMeasureOnViewA();
public void verifyMeasureOnViewC(); public void verifyMeasureOnViewC();
public void verifyMeasureLayoutCRelativeToA(); public void verifyMeasureLayoutCRelativeToA();
public void verifyMeasureLayoutCRelativeToB(); public void verifyMeasureLayoutCRelativeToB();
public void verifyMeasureLayoutCRelativeToSelf(); public void verifyMeasureLayoutCRelativeToSelf();
public void verifyMeasureLayoutRelativeToParentOnViewA(); public void verifyMeasureLayoutRelativeToParentOnViewA();
public void verifyMeasureLayoutRelativeToParentOnViewB(); public void verifyMeasureLayoutRelativeToParentOnViewB();
public void verifyMeasureLayoutRelativeToParentOnViewC(); public void verifyMeasureLayoutRelativeToParentOnViewC();
public void verifyMeasureLayoutDRelativeToB(); public void verifyMeasureLayoutDRelativeToB();
public void verifyMeasureLayoutNonExistentTag(); public void verifyMeasureLayoutNonExistentTag();
public void verifyMeasureLayoutNonExistentAncestor(); public void verifyMeasureLayoutNonExistentAncestor();
public void verifyMeasureLayoutRelativeToParentNonExistentTag(); public void verifyMeasureLayoutRelativeToParentNonExistentTag();
} }
@ -73,8 +69,7 @@ public class CatalystMeasureLayoutTest extends ReactAppInstrumentationTestCase {
@Override @Override
protected ReactInstanceSpecForTest createReactInstanceSpecForTest() { protected ReactInstanceSpecForTest createReactInstanceSpecForTest() {
mAssertModule = new AssertModule(); mAssertModule = new AssertModule();
return super.createReactInstanceSpecForTest() return super.createReactInstanceSpecForTest().addNativeModule(mAssertModule);
.addNativeModule(mAssertModule);
} }
private void waitForBridgeIdleAndVerifyAsserts() { private void waitForBridgeIdleAndVerifyAsserts() {

Просмотреть файл

@ -1,19 +1,16 @@
/** /**
* Copyright (c) Facebook, Inc. and its affiliates. * Copyright (c) Facebook, Inc. and its affiliates.
* *
* This source code is licensed under the MIT license found in the * <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* LICENSE file in the root directory of this source tree. * directory of this source tree.
*/ */
package com.facebook.react.tests; package com.facebook.react.tests;
import java.util.List;
import android.view.MotionEvent; import android.view.MotionEvent;
import com.facebook.react.testing.ReactInstanceSpecForTest;
import com.facebook.react.testing.ReactAppInstrumentationTestCase; import com.facebook.react.testing.ReactAppInstrumentationTestCase;
import com.facebook.react.testing.ReactInstanceSpecForTest;
import com.facebook.react.testing.StringRecordingModule; import com.facebook.react.testing.StringRecordingModule;
import java.util.List;
/** /**
* Test case for verifying that multitouch events are directed to the React's view touch handlers * Test case for verifying that multitouch events are directed to the React's view touch handlers
@ -30,8 +27,7 @@ public class CatalystMultitouchHandlingTestCase extends ReactAppInstrumentationT
@Override @Override
protected ReactInstanceSpecForTest createReactInstanceSpecForTest() { protected ReactInstanceSpecForTest createReactInstanceSpecForTest() {
return new ReactInstanceSpecForTest() return new ReactInstanceSpecForTest().addNativeModule(mRecordingModule);
.addNativeModule(mRecordingModule);
} }
/** /**
@ -102,12 +98,27 @@ public class CatalystMultitouchHandlingTestCase extends ReactAppInstrumentationT
final int pointerCount, final int pointerCount,
final MotionEvent.PointerProperties[] pointerProps, final MotionEvent.PointerProperties[] pointerProps,
final MotionEvent.PointerCoords[] pointerCoords) { final MotionEvent.PointerCoords[] pointerCoords) {
getRootView().post( getRootView()
.post(
new Runnable() { new Runnable() {
@Override @Override
public void run() { public void run() {
MotionEvent event = MotionEvent event =
MotionEvent.obtain(start, when, action, pointerCount, pointerProps, pointerCoords, 0, 0, 1.0f, 1.0f, 0, 0, 0, 0); MotionEvent.obtain(
start,
when,
action,
pointerCount,
pointerProps,
pointerCoords,
0,
0,
1.0f,
1.0f,
0,
0,
0,
0);
getRootView().dispatchTouchEvent(event); getRootView().dispatchTouchEvent(event);
event.recycle(); event.recycle();
} }
@ -117,11 +128,10 @@ public class CatalystMultitouchHandlingTestCase extends ReactAppInstrumentationT
/** /**
* This method "replay" multi-touch gesture recorded with modified TouchesHelper class that * This method "replay" multi-touch gesture recorded with modified TouchesHelper class that
* generated this piece of code (see https://phabricator.fb.com/P19756940). * generated this piece of code (see https://phabricator.fb.com/P19756940). This is not intended
* This is not intended to be copied/reused and once we need to have more multitouch gestures * to be copied/reused and once we need to have more multitouch gestures in instrumentation tests
* in instrumentation tests we should either: * we should either: - implement nice generator similar to {@link SingleTouchGestureGenerator} -
* - implement nice generator similar to {@link SingleTouchGestureGenerator} * implement gesture recorded that will record touch data using arbitrary format and then read
* - implement gesture recorded that will record touch data using arbitrary format and then read
* this recorded touch sequence during tests instead of generating code like this * this recorded touch sequence during tests instead of generating code like this
*/ */
private void generateRecordedPinchTouchEvents() { private void generateRecordedPinchTouchEvents() {
@ -149,7 +159,13 @@ public class CatalystMultitouchHandlingTestCase extends ReactAppInstrumentationT
pointerCoords[0] = createPointerCoords(267.0f, 346.0f); pointerCoords[0] = createPointerCoords(267.0f, 346.0f);
pointerProps[1] = createPointerProps(1, 1); pointerProps[1] = createPointerProps(1, 1);
pointerCoords[1] = createPointerCoords(225.0f, 542.0f); pointerCoords[1] = createPointerCoords(225.0f, 542.0f);
dispatchEvent(MotionEvent.ACTION_POINTER_DOWN | (1 << MotionEvent.ACTION_POINTER_INDEX_SHIFT), 446560605, 446560630, 2, pointerProps, pointerCoords); dispatchEvent(
MotionEvent.ACTION_POINTER_DOWN | (1 << MotionEvent.ACTION_POINTER_INDEX_SHIFT),
446560605,
446560630,
2,
pointerProps,
pointerCoords);
} }
{ {
@ -639,7 +655,13 @@ public class CatalystMultitouchHandlingTestCase extends ReactAppInstrumentationT
pointerCoords[0] = createPointerCoords(349.0f, 110.0f); pointerCoords[0] = createPointerCoords(349.0f, 110.0f);
pointerProps[1] = createPointerProps(1, 1); pointerProps[1] = createPointerProps(1, 1);
pointerCoords[1] = createPointerCoords(151.0f, 680.0f); pointerCoords[1] = createPointerCoords(151.0f, 680.0f);
dispatchEvent(MotionEvent.ACTION_POINTER_UP | (0 << MotionEvent.ACTION_POINTER_INDEX_SHIFT), 446560605, 446561443, 2, pointerProps, pointerCoords); dispatchEvent(
MotionEvent.ACTION_POINTER_UP | (0 << MotionEvent.ACTION_POINTER_INDEX_SHIFT),
446560605,
446561443,
2,
pointerProps,
pointerCoords);
} }
{ {
@ -651,5 +673,4 @@ public class CatalystMultitouchHandlingTestCase extends ReactAppInstrumentationT
} }
// END OF GENERATED CODE // END OF GENERATED CODE
} }
} }

Просмотреть файл

@ -1,10 +1,9 @@
/** /**
* Copyright (c) Facebook, Inc. and its affiliates. * Copyright (c) Facebook, Inc. and its affiliates.
* *
* This source code is licensed under the MIT license found in the * <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* LICENSE file in the root directory of this source tree. * directory of this source tree.
*/ */
package com.facebook.react.tests; package com.facebook.react.tests;
import com.facebook.react.bridge.BaseJavaModule; import com.facebook.react.bridge.BaseJavaModule;
@ -44,35 +43,45 @@ import org.junit.Ignore;
/** /**
* Integration test to verify passing various types of parameters from JS to Java works * Integration test to verify passing various types of parameters from JS to Java works
* *
* TODO: we should run these tests with isBlockingSynchronousMethod = true as well, * <p>TODO: we should run these tests with isBlockingSynchronousMethod = true as well, since they
* since they currently use a completely different codepath * currently use a completely different codepath
*/ */
@Ignore("Fix prop types and view managers.") @Ignore("Fix prop types and view managers.")
public class CatalystNativeJSToJavaParametersTestCase extends ReactIntegrationTestCase { public class CatalystNativeJSToJavaParametersTestCase extends ReactIntegrationTestCase {
private interface TestJSToJavaParametersModule extends JavaScriptModule { private interface TestJSToJavaParametersModule extends JavaScriptModule {
void returnBasicTypes(); void returnBasicTypes();
void returnBoxedTypes(); void returnBoxedTypes();
void returnDynamicTypes(); void returnDynamicTypes();
void returnArrayWithBasicTypes(); void returnArrayWithBasicTypes();
void returnNestedArray(); void returnNestedArray();
void returnArrayWithMaps(); void returnArrayWithMaps();
void returnMapWithBasicTypes(); void returnMapWithBasicTypes();
void returnNestedMap(); void returnNestedMap();
void returnMapWithArrays(); void returnMapWithArrays();
void returnArrayWithStringDoubleIntMapArrayBooleanNull(); void returnArrayWithStringDoubleIntMapArrayBooleanNull();
void returnMapWithStringDoubleIntMapArrayBooleanNull(); void returnMapWithStringDoubleIntMapArrayBooleanNull();
void returnMapForMerge1(); void returnMapForMerge1();
void returnMapForMerge2(); void returnMapForMerge2();
void returnMapWithMultibyteUTF8CharacterString(); void returnMapWithMultibyteUTF8CharacterString();
void returnArrayWithMultibyteUTF8CharacterString(); void returnArrayWithMultibyteUTF8CharacterString();
void returnArrayWithLargeInts(); void returnArrayWithLargeInts();
void returnMapWithLargeInts(); void returnMapWithLargeInts();
} }
@ -83,10 +92,8 @@ public class CatalystNativeJSToJavaParametersTestCase extends ReactIntegrationTe
protected void setUp() throws Exception { protected void setUp() throws Exception {
super.setUp(); super.setUp();
List<ViewManager> viewManagers = Arrays.<ViewManager>asList( List<ViewManager> viewManagers = Arrays.<ViewManager>asList(new ReactViewManager());
new ReactViewManager()); final UIManagerModule mUIManager = new UIManagerModule(getContext(), viewManagers, 0);
final UIManagerModule mUIManager =
new UIManagerModule(getContext(), viewManagers, 0);
UiThreadUtil.runOnUiThread( UiThreadUtil.runOnUiThread(
new Runnable() { new Runnable() {
@Override @Override
@ -97,7 +104,8 @@ public class CatalystNativeJSToJavaParametersTestCase extends ReactIntegrationTe
waitForIdleSync(); waitForIdleSync();
mRecordingTestModule = new RecordingTestModule(); mRecordingTestModule = new RecordingTestModule();
mCatalystInstance = ReactTestHelper.catalystInstanceBuilder(this) mCatalystInstance =
ReactTestHelper.catalystInstanceBuilder(this)
.addNativeModule(mRecordingTestModule) .addNativeModule(mRecordingTestModule)
.addNativeModule(new AndroidInfoModule(getContext())) .addNativeModule(new AndroidInfoModule(getContext()))
.addNativeModule(new DeviceInfoModule(getContext())) .addNativeModule(new DeviceInfoModule(getContext()))
@ -314,7 +322,8 @@ public class CatalystNativeJSToJavaParametersTestCase extends ReactIntegrationTe
} }
public void testGetTypeFromArray() { public void testGetTypeFromArray() {
mCatalystInstance.getJSModule(TestJSToJavaParametersModule.class) mCatalystInstance
.getJSModule(TestJSToJavaParametersModule.class)
.returnArrayWithStringDoubleIntMapArrayBooleanNull(); .returnArrayWithStringDoubleIntMapArrayBooleanNull();
waitForBridgeAndUIIdle(); waitForBridgeAndUIIdle();
@ -332,7 +341,8 @@ public class CatalystNativeJSToJavaParametersTestCase extends ReactIntegrationTe
} }
public void testGetTypeFromMap() { public void testGetTypeFromMap() {
mCatalystInstance.getJSModule(TestJSToJavaParametersModule.class) mCatalystInstance
.getJSModule(TestJSToJavaParametersModule.class)
.returnMapWithStringDoubleIntMapArrayBooleanNull(); .returnMapWithStringDoubleIntMapArrayBooleanNull();
waitForBridgeAndUIIdle(); waitForBridgeAndUIIdle();
@ -350,7 +360,8 @@ public class CatalystNativeJSToJavaParametersTestCase extends ReactIntegrationTe
} }
public void testGetWrongTypeFromArray() { public void testGetWrongTypeFromArray() {
mCatalystInstance.getJSModule(TestJSToJavaParametersModule.class) mCatalystInstance
.getJSModule(TestJSToJavaParametersModule.class)
.returnArrayWithStringDoubleIntMapArrayBooleanNull(); .returnArrayWithStringDoubleIntMapArrayBooleanNull();
waitForBridgeAndUIIdle(); waitForBridgeAndUIIdle();
@ -367,7 +378,8 @@ public class CatalystNativeJSToJavaParametersTestCase extends ReactIntegrationTe
} }
public void testGetWrongTypeFromMap() { public void testGetWrongTypeFromMap() {
mCatalystInstance.getJSModule(TestJSToJavaParametersModule.class) mCatalystInstance
.getJSModule(TestJSToJavaParametersModule.class)
.returnMapWithStringDoubleIntMapArrayBooleanNull(); .returnMapWithStringDoubleIntMapArrayBooleanNull();
waitForBridgeAndUIIdle(); waitForBridgeAndUIIdle();
@ -595,7 +607,8 @@ public class CatalystNativeJSToJavaParametersTestCase extends ReactIntegrationTe
keys.add(mapIterator.nextKey()); keys.add(mapIterator.nextKey());
} }
Set<String> expectedKeys = new HashSet<String>( Set<String> expectedKeys =
new HashSet<String>(
Arrays.asList("stringKey", "doubleKey", "intKey", "booleanKey", "nullKey")); Arrays.asList("stringKey", "doubleKey", "intKey", "booleanKey", "nullKey"));
assertEquals(keys, expectedKeys); assertEquals(keys, expectedKeys);
} }
@ -669,9 +682,7 @@ public class CatalystNativeJSToJavaParametersTestCase extends ReactIntegrationTe
} }
private void assertUnexpectedTypeExceptionThrown( private void assertUnexpectedTypeExceptionThrown(
ReadableArray array, ReadableArray array, int index, String typeToAskFor) {
int index,
String typeToAskFor) {
boolean gotException = false; boolean gotException = false;
try { try {
arrayGetByType(array, index, typeToAskFor); arrayGetByType(array, index, typeToAskFor);
@ -683,9 +694,7 @@ public class CatalystNativeJSToJavaParametersTestCase extends ReactIntegrationTe
} }
private void assertUnexpectedTypeExceptionThrown( private void assertUnexpectedTypeExceptionThrown(
ReadableMap map, ReadableMap map, String key, String typeToAskFor) {
String key,
String typeToAskFor) {
boolean gotException = false; boolean gotException = false;
try { try {
mapGetByType(map, key, typeToAskFor); mapGetByType(map, key, typeToAskFor);
@ -697,9 +706,7 @@ public class CatalystNativeJSToJavaParametersTestCase extends ReactIntegrationTe
} }
private void assertArrayOutOfBoundsExceptionThrown( private void assertArrayOutOfBoundsExceptionThrown(
ReadableArray array, ReadableArray array, int index, String typeToAskFor) {
int index,
String typeToAskFor) {
boolean gotException = false; boolean gotException = false;
try { try {
arrayGetByType(array, index, typeToAskFor); arrayGetByType(array, index, typeToAskFor);
@ -710,10 +717,7 @@ public class CatalystNativeJSToJavaParametersTestCase extends ReactIntegrationTe
assertTrue(gotException); assertTrue(gotException);
} }
private void assertNoSuchKeyExceptionThrown( private void assertNoSuchKeyExceptionThrown(ReadableMap map, String key, String typeToAskFor) {
ReadableMap map,
String key,
String typeToAskFor) {
boolean gotException = false; boolean gotException = false;
try { try {
mapGetByType(map, key, typeToAskFor); mapGetByType(map, key, typeToAskFor);
@ -724,8 +728,7 @@ public class CatalystNativeJSToJavaParametersTestCase extends ReactIntegrationTe
assertTrue(gotException); assertTrue(gotException);
} }
private static void assertInvalidIteratorExceptionThrown( private static void assertInvalidIteratorExceptionThrown(ReadableMapKeySetIterator iterator) {
ReadableMapKeySetIterator iterator) {
boolean gotException = false; boolean gotException = false;
try { try {
iterator.nextKey(); iterator.nextKey();

Просмотреть файл

@ -1,10 +1,9 @@
/** /**
* Copyright (c) Facebook, Inc. and its affiliates. * Copyright (c) Facebook, Inc. and its affiliates.
* *
* This source code is licensed under the MIT license found in the * <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* LICENSE file in the root directory of this source tree. * directory of this source tree.
*/ */
package com.facebook.react.tests; package com.facebook.react.tests;
import com.facebook.react.bridge.CatalystInstance; import com.facebook.react.bridge.CatalystInstance;
@ -28,9 +27,7 @@ import java.util.Arrays;
import java.util.List; import java.util.List;
import org.junit.Ignore; import org.junit.Ignore;
/** /** Test marshalling arguments from Java to JS to appropriate native classes. */
* Test marshalling arguments from Java to JS to appropriate native classes.
*/
@Ignore("Fix prop types and view managers.") @Ignore("Fix prop types and view managers.")
public class CatalystNativeJavaToJSArgumentsTestCase extends ReactIntegrationTestCase { public class CatalystNativeJavaToJSArgumentsTestCase extends ReactIntegrationTestCase {
@ -38,16 +35,21 @@ public class CatalystNativeJavaToJSArgumentsTestCase extends ReactIntegrationTes
void receiveBasicTypes(String s, double d, boolean b, String nullString); void receiveBasicTypes(String s, double d, boolean b, String nullString);
void receiveArrayWithBasicTypes(WritableArray array); void receiveArrayWithBasicTypes(WritableArray array);
void receiveNestedArray(WritableArray nestedArray); void receiveNestedArray(WritableArray nestedArray);
void receiveArrayWithMaps(WritableArray arrayWithMaps); void receiveArrayWithMaps(WritableArray arrayWithMaps);
void receiveMapWithBasicTypes(WritableMap map); void receiveMapWithBasicTypes(WritableMap map);
void receiveNestedMap(WritableMap nestedMap); void receiveNestedMap(WritableMap nestedMap);
void receiveMapWithArrays(WritableMap mapWithArrays); void receiveMapWithArrays(WritableMap mapWithArrays);
void receiveMapAndArrayWithNullValues(
WritableMap map, void receiveMapAndArrayWithNullValues(WritableMap map, WritableArray array);
WritableArray array);
void receiveMapWithMultibyteUTF8CharacterString(WritableMap map); void receiveMapWithMultibyteUTF8CharacterString(WritableMap map);
void receiveArrayWithMultibyteUTF8CharacterString(WritableArray array); void receiveArrayWithMultibyteUTF8CharacterString(WritableArray array);
} }
@ -58,10 +60,8 @@ public class CatalystNativeJavaToJSArgumentsTestCase extends ReactIntegrationTes
protected void setUp() throws Exception { protected void setUp() throws Exception {
super.setUp(); super.setUp();
List<ViewManager> viewManagers = Arrays.<ViewManager>asList( List<ViewManager> viewManagers = Arrays.<ViewManager>asList(new ReactViewManager());
new ReactViewManager()); final UIManagerModule mUIManager = new UIManagerModule(getContext(), viewManagers, 0);
final UIManagerModule mUIManager =
new UIManagerModule(getContext(), viewManagers, 0);
UiThreadUtil.runOnUiThread( UiThreadUtil.runOnUiThread(
new Runnable() { new Runnable() {
@Override @Override
@ -73,7 +73,8 @@ public class CatalystNativeJavaToJSArgumentsTestCase extends ReactIntegrationTes
mAssertModule = new AssertModule(); mAssertModule = new AssertModule();
mInstance = ReactTestHelper.catalystInstanceBuilder(this) mInstance =
ReactTestHelper.catalystInstanceBuilder(this)
.addNativeModule(mAssertModule) .addNativeModule(mAssertModule)
.addNativeModule(new DeviceInfoModule(getContext())) .addNativeModule(new DeviceInfoModule(getContext()))
.addNativeModule(new AppStateModule(getContext())) .addNativeModule(new AppStateModule(getContext()))
@ -83,7 +84,8 @@ public class CatalystNativeJavaToJSArgumentsTestCase extends ReactIntegrationTes
} }
public void testBasicTypes() { public void testBasicTypes() {
mInstance.getJSModule(TestJavaToJSArgumentsModule.class) mInstance
.getJSModule(TestJavaToJSArgumentsModule.class)
.receiveBasicTypes("foo", 3.14, true, null); .receiveBasicTypes("foo", 3.14, true, null);
waitForBridgeAndUIIdle(); waitForBridgeAndUIIdle();
mAssertModule.verifyAssertsAndReset(); mAssertModule.verifyAssertsAndReset();
@ -182,7 +184,8 @@ public class CatalystNativeJavaToJSArgumentsTestCase extends ReactIntegrationTes
array.pushArray(null); array.pushArray(null);
array.pushMap(null); array.pushMap(null);
mInstance.getJSModule(TestJavaToJSArgumentsModule.class) mInstance
.getJSModule(TestJavaToJSArgumentsModule.class)
.receiveMapAndArrayWithNullValues(map, array); .receiveMapAndArrayWithNullValues(map, array);
waitForBridgeAndUIIdle(); waitForBridgeAndUIIdle();
mAssertModule.verifyAssertsAndReset(); mAssertModule.verifyAssertsAndReset();

Просмотреть файл

@ -1,10 +1,9 @@
/** /**
* Copyright (c) Facebook, Inc. and its affiliates. * Copyright (c) Facebook, Inc. and its affiliates.
* *
* This source code is licensed under the MIT license found in the * <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* LICENSE file in the root directory of this source tree. * directory of this source tree.
*/ */
package com.facebook.react.tests; package com.facebook.react.tests;
import com.facebook.react.bridge.BaseJavaModule; import com.facebook.react.bridge.BaseJavaModule;
@ -27,14 +26,13 @@ import com.facebook.react.uimanager.ViewManager;
import java.util.ArrayList; import java.util.ArrayList;
import org.junit.Ignore; import org.junit.Ignore;
/** /** Test marshalling return values from Java to JS */
* Test marshalling return values from Java to JS
*/
@Ignore("Fix prop types and view managers.") @Ignore("Fix prop types and view managers.")
public class CatalystNativeJavaToJSReturnValuesTestCase extends ReactIntegrationTestCase { public class CatalystNativeJavaToJSReturnValuesTestCase extends ReactIntegrationTestCase {
private interface TestJavaToJSReturnValuesModule extends JavaScriptModule { private interface TestJavaToJSReturnValuesModule extends JavaScriptModule {
void callMethod(String methodName, String expectedReturnType, String expectedJSON); void callMethod(String methodName, String expectedReturnType, String expectedJSON);
void triggerException(); void triggerException();
} }
@ -110,12 +108,12 @@ public class CatalystNativeJavaToJSReturnValuesTestCase extends ReactIntegration
super.setUp(); super.setUp();
final UIManagerModule mUIManager = final UIManagerModule mUIManager =
new UIManagerModule( new UIManagerModule(getContext(), new ArrayList<ViewManager>(), 0);
getContext(), new ArrayList<ViewManager>(), 0);
mAssertModule = new AssertModule(); mAssertModule = new AssertModule();
mInstance = ReactTestHelper.catalystInstanceBuilder(this) mInstance =
ReactTestHelper.catalystInstanceBuilder(this)
.addNativeModule(mAssertModule) .addNativeModule(mAssertModule)
.addNativeModule(new DeviceInfoModule(getContext())) .addNativeModule(new DeviceInfoModule(getContext()))
.addNativeModule(new AppStateModule(getContext())) .addNativeModule(new AppStateModule(getContext()))

Просмотреть файл

@ -1,30 +1,25 @@
/** /**
* Copyright (c) Facebook, Inc. and its affiliates. * Copyright (c) Facebook, Inc. and its affiliates.
* *
* This source code is licensed under the MIT license found in the * <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* LICENSE file in the root directory of this source tree. * directory of this source tree.
*/ */
package com.facebook.react.tests; package com.facebook.react.tests;
import java.util.ArrayList;
import java.util.List;
import android.content.Context; import android.content.Context;
import javax.annotation.Nullable;
import android.widget.ScrollView; import android.widget.ScrollView;
import com.facebook.react.bridge.JavaScriptModule; import com.facebook.react.bridge.JavaScriptModule;
import com.facebook.react.testing.ReactAppInstrumentationTestCase; import com.facebook.react.testing.ReactAppInstrumentationTestCase;
import com.facebook.react.testing.ReactInstanceSpecForTest; import com.facebook.react.testing.ReactInstanceSpecForTest;
import com.facebook.react.uimanager.PixelUtil; import com.facebook.react.uimanager.PixelUtil;
import com.facebook.react.uimanager.annotations.ReactProp;
import com.facebook.react.uimanager.ThemedReactContext; import com.facebook.react.uimanager.ThemedReactContext;
import com.facebook.react.uimanager.annotations.ReactProp;
import com.facebook.react.views.view.ReactViewGroup; import com.facebook.react.views.view.ReactViewGroup;
import com.facebook.react.views.view.ReactViewManager; import com.facebook.react.views.view.ReactViewManager;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Nullable;
import org.junit.Assert; import org.junit.Assert;
import org.junit.Ignore;
/** /**
* Integration test for {@code removeClippedSubviews} property that verify correct scrollview * Integration test for {@code removeClippedSubviews} property that verify correct scrollview
@ -34,9 +29,13 @@ public class CatalystSubviewsClippingTestCase extends ReactAppInstrumentationTes
private interface SubviewsClippingTestModule extends JavaScriptModule { private interface SubviewsClippingTestModule extends JavaScriptModule {
void renderClippingSample1(); void renderClippingSample1();
void renderClippingSample2(); void renderClippingSample2();
void renderScrollViewTest(); void renderScrollViewTest();
void renderUpdatingSample1(boolean update1, boolean update2); void renderUpdatingSample1(boolean update1, boolean update2);
void renderUpdatingSample2(boolean update); void renderUpdatingSample2(boolean update);
} }
@ -49,31 +48,18 @@ public class CatalystSubviewsClippingTestCase extends ReactAppInstrumentationTes
@Override @Override
protected ReactInstanceSpecForTest createReactInstanceSpecForTest() { protected ReactInstanceSpecForTest createReactInstanceSpecForTest() {
return super.createReactInstanceSpecForTest() return super.createReactInstanceSpecForTest().addViewManager(new ClippableViewManager(mEvents));
.addViewManager(new ClippableViewManager(mEvents));
} }
/** /**
* In this test view are layout in a following way: * In this test view are layout in a following way: +-----------------------------+ | | |
* +-----------------------------+ * +---------------------+ | | | inner1 | | | +---------------------+ | |
* | | * +-------------------------+ | | | outer (clip=true) | | | | +---------------------+ | | | | |
* | +---------------------+ | * inner2 | | | | | +---------------------+ | | | | | | | +-------------------------+ | |
* | | inner1 | | * +---------------------+ | | | inner3 | | | +---------------------+ | | |
* | +---------------------+ |
* | +-------------------------+ |
* | | outer (clip=true) | |
* | | +---------------------+ | |
* | | | inner2 | | |
* | | +---------------------+ | |
* | | | |
* | +-------------------------+ |
* | +---------------------+ |
* | | inner3 | |
* | +---------------------+ |
* | |
* +-----------------------------+ * +-----------------------------+
* *
* We expect only outer and inner2 to be attached * <p>We expect only outer and inner2 to be attached
*/ */
public void XtestOneLevelClippingInView() throws Throwable { public void XtestOneLevelClippingInView() throws Throwable {
mEvents.clear(); mEvents.clear();
@ -83,44 +69,29 @@ public class CatalystSubviewsClippingTestCase extends ReactAppInstrumentationTes
} }
/** /**
* In this test view are layout in a following way: * In this test view are layout in a following way: +-----------------------------+ | outer
* +-----------------------------+ * (clip=true) | | | | | | | | +-----------------------------+ | | complexInner (clip=true) | | |
* | outer (clip=true) | * +----------+ | +---------+ | | | | inner1 | | | inner2 | | | | | | | | | | | | +----------+ |
* | | * +---------+ | +--------------+--------------+ | | +----------+ +---------+ | | | inner3 | |
* | | * inner4 | | | | | | | | | +----------+ +---------+ | | | +-----------------------------+
* | |
* | +-----------------------------+
* | | complexInner (clip=true) |
* | | +----------+ | +---------+ |
* | | | inner1 | | | inner2 | |
* | | | | | | | |
* | | +----------+ | +---------+ |
* +--------------+--------------+ |
* | +----------+ +---------+ |
* | | inner3 | | inner4 | |
* | | | | | |
* | +----------+ +---------+ |
* | |
* +-----------------------------+
* *
* We expect outer, complexInner & inner1 to be attached * <p>We expect outer, complexInner & inner1 to be attached
*/ */
public void XtestTwoLevelClippingInView() throws Throwable { public void XtestTwoLevelClippingInView() throws Throwable {
mEvents.clear(); mEvents.clear();
getReactContext().getJSModule(SubviewsClippingTestModule.class).renderClippingSample2(); getReactContext().getJSModule(SubviewsClippingTestModule.class).renderClippingSample2();
waitForBridgeAndUIIdle(); waitForBridgeAndUIIdle();
Assert.assertArrayEquals( Assert.assertArrayEquals(
new String[]{"Attach_outer", "Attach_complexInner", "Attach_inner1"}, new String[] {"Attach_outer", "Attach_complexInner", "Attach_inner1"}, mEvents.toArray());
mEvents.toArray());
} }
/** /**
* This test verifies that we update clipped subviews appropriately when some of them gets * This test verifies that we update clipped subviews appropriately when some of them gets
* re-layouted. * re-layouted.
* *
* In this test scenario we render clipping view ("outer") with two subviews, one is outside and * <p>In this test scenario we render clipping view ("outer") with two subviews, one is outside
* clipped and one is inside (absolutely positioned). By updating view props we first change the * and clipped and one is inside (absolutely positioned). By updating view props we first change
* height of the first element so that it should intersect with clipping "outer" view. Then we * the height of the first element so that it should intersect with clipping "outer" view. Then we
* update top position of the second view so that is should go off screen. * update top position of the second view so that is should go off screen.
*/ */
public void testClippingAfterLayoutInner() { public void testClippingAfterLayoutInner() {
@ -147,7 +118,7 @@ public class CatalystSubviewsClippingTestCase extends ReactAppInstrumentationTes
* This test verifies that we update clipping views appropriately when parent view layout changes * This test verifies that we update clipping views appropriately when parent view layout changes
* in a way that affects clipping. * in a way that affects clipping.
* *
* In this test we render clipping view ("outer") set to be 100x100dp with inner view that is * <p>In this test we render clipping view ("outer") set to be 100x100dp with inner view that is
* absolutely positioned out of the clipping area of the parent view. Then we resize parent view * absolutely positioned out of the clipping area of the parent view. Then we resize parent view
* so that inner view should be visible. * so that inner view should be visible.
*/ */

Просмотреть файл

@ -1,51 +1,35 @@
/** /**
* Copyright (c) Facebook, Inc. and its affiliates. * Copyright (c) Facebook, Inc. and its affiliates.
* *
* This source code is licensed under the MIT license found in the * <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* LICENSE file in the root directory of this source tree. * directory of this source tree.
*/ */
package com.facebook.react.tests; package com.facebook.react.tests;
import android.view.View; import android.view.View;
import com.facebook.react.testing.ReactInstanceSpecForTest;
import com.facebook.react.testing.ReactAppInstrumentationTestCase; import com.facebook.react.testing.ReactAppInstrumentationTestCase;
import com.facebook.react.testing.ReactInstanceSpecForTest;
import com.facebook.react.testing.SingleTouchGestureGenerator; import com.facebook.react.testing.SingleTouchGestureGenerator;
import com.facebook.react.testing.StringRecordingModule; import com.facebook.react.testing.StringRecordingModule;
/** /**
* This test is to verify that touch events bubbles up to the right handler. We emulate couple * This test is to verify that touch events bubbles up to the right handler. We emulate couple of
* of different gestures on top of the application reflecting following layout: * different gestures on top of the application reflecting following layout:
* *
* +---------------------------------------------------------------------------------------+ * <p>+---------------------------------------------------------------------------------------+ | |
* | | * | +----------------------------------------------------------------------------------+ | | |
* | +----------------------------------------------------------------------------------+ | * +-------------+ +----------------+ | | | | | +---+ | | | | | | | | | A | | | | | | | | | +---+ |
* | | +-------------+ +----------------+ | | * | C | | | | | | {B} | | | | | | | | | {D} | | | | | | +-------------+ +----------------+ | | | |
* | | | +---+ | | | | | * | | | | | | |
* | | | | A | | | | | | * +----------------------------------------------------------------------------------+ | | |
* | | | +---+ | | C | | | * +----------------------------------------------------------------------------------+ | | | | | |
* | | | {B} | | | | | * | | | | | | | | | {E} | | | | | | | | | | |
* | | | | {D} | | | | * +----------------------------------------------------------------------------------+ |
* | | +-------------+ +----------------+ | |
* | | | |
* | | | |
* | +----------------------------------------------------------------------------------+ |
* |
* | +----------------------------------------------------------------------------------+ |
* | | | |
* | | | |
* | | | |
* | | {E} | |
* | | | |
* | | | |
* | +----------------------------------------------------------------------------------+ |
* +---------------------------------------------------------------------------------------+ * +---------------------------------------------------------------------------------------+
* *
* Then in each test case we either tap the center of a particular view (from A to E) or we start * <p>Then in each test case we either tap the center of a particular view (from A to E) or we start
* a gesture in one view and end it with another. * a gesture in one view and end it with another. View with names in brackets (e.g. {D}) have touch
* View with names in brackets (e.g. {D}) have touch handlers set whereas all other views are not * handlers set whereas all other views are not declared to handler touch events.
* declared to handler touch events.
*/ */
public class CatalystTouchBubblingTestCase extends ReactAppInstrumentationTestCase { public class CatalystTouchBubblingTestCase extends ReactAppInstrumentationTestCase {
@ -57,8 +41,8 @@ public class CatalystTouchBubblingTestCase extends ReactAppInstrumentationTestCa
} }
/** /**
* 1) Simulate touch event at view A, expect {B} touch handler to fire * 1) Simulate touch event at view A, expect {B} touch handler to fire 2) Simulate touch event at
* 2) Simulate touch event at view C, expect {D} touch handler to fire * view C, expect {D} touch handler to fire
*/ */
public void testSimpleClickAtInnerElements() { public void testSimpleClickAtInnerElements() {
mRecordingModule.reset(); mRecordingModule.reset();
@ -80,8 +64,7 @@ public class CatalystTouchBubblingTestCase extends ReactAppInstrumentationTestCa
/** /**
* 1) Start touch at view A, then drag and release on view {B} (but outside of A), expect {B}'s * 1) Start touch at view A, then drag and release on view {B} (but outside of A), expect {B}'s
* touch handler to fire * touch handler to fire 2) Do the same with view C and {D}
* 2) Do the same with view C and {D}
*/ */
public void testDownOnInnerUpOnTouchableParent() { public void testDownOnInnerUpOnTouchableParent() {
View innerButton = getViewByTestId("A"); View innerButton = getViewByTestId("A");
@ -151,7 +134,6 @@ public class CatalystTouchBubblingTestCase extends ReactAppInstrumentationTestCa
@Override @Override
protected ReactInstanceSpecForTest createReactInstanceSpecForTest() { protected ReactInstanceSpecForTest createReactInstanceSpecForTest() {
return new ReactInstanceSpecForTest() return new ReactInstanceSpecForTest().addNativeModule(mRecordingModule);
.addNativeModule(mRecordingModule);
} }
} }

Просмотреть файл

@ -1,10 +1,9 @@
/** /**
* Copyright (c) Facebook, Inc. and its affiliates. * Copyright (c) Facebook, Inc. and its affiliates.
* *
* This source code is licensed under the MIT license found in the * <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* LICENSE file in the root directory of this source tree. * directory of this source tree.
*/ */
package com.facebook.react.tests; package com.facebook.react.tests;
import android.util.DisplayMetrics; import android.util.DisplayMetrics;
@ -30,17 +29,21 @@ import com.facebook.react.views.view.ReactViewManager;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
/** /** Test case for basic {@link UIManagerModule} functionality. */
* Test case for basic {@link UIManagerModule} functionality.
*/
public class CatalystUIManagerTestCase extends ReactIntegrationTestCase { public class CatalystUIManagerTestCase extends ReactIntegrationTestCase {
private interface UIManagerTestModule extends JavaScriptModule { private interface UIManagerTestModule extends JavaScriptModule {
void renderFlexTestApplication(int rootTag); void renderFlexTestApplication(int rootTag);
void renderFlexWithTextApplication(int rootTag); void renderFlexWithTextApplication(int rootTag);
void renderAbsolutePositionTestApplication(int rootTag); void renderAbsolutePositionTestApplication(int rootTag);
void renderAbsolutePositionBottomRightTestApplication(int rootTag); void renderAbsolutePositionBottomRightTestApplication(int rootTag);
void renderCenteredTextViewTestApplication(int rootTag, String text); void renderCenteredTextViewTestApplication(int rootTag, String text);
void renderUpdatePositionInListTestApplication(int rootTag); void renderUpdatePositionInListTestApplication(int rootTag);
void flushUpdatePositionInList(); void flushUpdatePositionInList();
} }
@ -71,13 +74,12 @@ public class CatalystUIManagerTestCase extends ReactIntegrationTestCase {
protected void setUp() throws Exception { protected void setUp() throws Exception {
super.setUp(); super.setUp();
List<ViewManager> viewManagers = Arrays.<ViewManager>asList( List<ViewManager> viewManagers =
new ReactViewManager(), Arrays.<ViewManager>asList(
new ReactTextViewManager(), new ReactViewManager(), new ReactTextViewManager(), new ReactRawTextManager());
new ReactRawTextManager()); uiManager = new UIManagerModule(getContext(), viewManagers, 0);
uiManager = UiThreadUtil.runOnUiThread(
new UIManagerModule(getContext(), viewManagers, 0); new Runnable() {
UiThreadUtil.runOnUiThread(new Runnable() {
@Override @Override
public void run() { public void run() {
uiManager.onHostResume(); uiManager.onHostResume();
@ -85,7 +87,8 @@ public class CatalystUIManagerTestCase extends ReactIntegrationTestCase {
}); });
waitForIdleSync(); waitForIdleSync();
jsModule = ReactTestHelper.catalystInstanceBuilder(this) jsModule =
ReactTestHelper.catalystInstanceBuilder(this)
.addNativeModule(uiManager) .addNativeModule(uiManager)
.addNativeModule(new AndroidInfoModule(getContext())) .addNativeModule(new AndroidInfoModule(getContext()))
.addNativeModule(new DeviceInfoModule(getContext())) .addNativeModule(new DeviceInfoModule(getContext()))
@ -134,7 +137,8 @@ public class CatalystUIManagerTestCase extends ReactIntegrationTestCase {
// assertEquals(inPixelRounded(300), row.getHeight()); // assertEquals(inPixelRounded(300), row.getHeight());
// assertEquals(2, row.getChildCount()); // assertEquals(2, row.getChildCount());
// //
// // Text measurement adds padding that isn't completely dependent on density so we can't easily // // Text measurement adds padding that isn't completely dependent on density so we can't
// easily
// // get an exact value here // // get an exact value here
// float approximateExpectedTextHeight = inPixelRounded(19); // float approximateExpectedTextHeight = inPixelRounded(19);
// View leftText = row.getChildAt(0); // View leftText = row.getChildAt(0);
@ -240,9 +244,9 @@ public class CatalystUIManagerTestCase extends ReactIntegrationTestCase {
} }
public void testCenteredTextCases() { public void testCenteredTextCases() {
String[] cases = new String[] { String[] cases =
"test", new String[] {
"with whitespace", "test", "with whitespace",
}; };
for (String text : cases) { for (String text : cases) {
_testCenteredText(text); _testCenteredText(text);

Просмотреть файл

@ -1,34 +1,29 @@
/** /**
* Copyright (c) Facebook, Inc. and its affiliates. * Copyright (c) Facebook, Inc. and its affiliates.
* *
* This source code is licensed under the MIT license found in the * <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* LICENSE file in the root directory of this source tree. * directory of this source tree.
*/ */
package com.facebook.react.tests; package com.facebook.react.tests;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import android.app.DatePickerDialog; import android.app.DatePickerDialog;
import android.content.DialogInterface; import android.content.DialogInterface;
import android.widget.DatePicker;
import androidx.fragment.app.DialogFragment; import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.Fragment; import androidx.fragment.app.Fragment;
import android.widget.DatePicker;
import com.facebook.react.bridge.BaseJavaModule; import com.facebook.react.bridge.BaseJavaModule;
import com.facebook.react.testing.ReactInstanceSpecForTest;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.JavaScriptModule; import com.facebook.react.bridge.JavaScriptModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.WritableMap; import com.facebook.react.bridge.WritableMap;
import com.facebook.react.bridge.WritableNativeMap; import com.facebook.react.bridge.WritableNativeMap;
import com.facebook.react.modules.datepicker.DatePickerDialogModule; import com.facebook.react.modules.datepicker.DatePickerDialogModule;
import com.facebook.react.testing.ReactAppInstrumentationTestCase; import com.facebook.react.testing.ReactAppInstrumentationTestCase;
import com.facebook.react.testing.ReactInstanceSpecForTest;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
/** /** Test case for {@link DatePickerDialogModule} options and callbacks. */
* Test case for {@link DatePickerDialogModule} options and callbacks.
*/
public class DatePickerDialogTestCase extends ReactAppInstrumentationTestCase { public class DatePickerDialogTestCase extends ReactAppInstrumentationTestCase {
private static interface DatePickerDialogTestModule extends JavaScriptModule { private static interface DatePickerDialogTestModule extends JavaScriptModule {
@ -78,8 +73,7 @@ public class DatePickerDialogTestCase extends ReactAppInstrumentationTestCase {
@Override @Override
protected ReactInstanceSpecForTest createReactInstanceSpecForTest() { protected ReactInstanceSpecForTest createReactInstanceSpecForTest() {
return super.createReactInstanceSpecForTest() return super.createReactInstanceSpecForTest().addNativeModule(mRecordingModule);
.addNativeModule(mRecordingModule);
} }
@Override @Override
@ -105,7 +99,9 @@ public class DatePickerDialogTestCase extends ReactAppInstrumentationTestCase {
waitForBridgeAndUIIdle(); waitForBridgeAndUIIdle();
getInstrumentation().waitForIdleSync(); getInstrumentation().waitForIdleSync();
return (DialogFragment) getActivity().getSupportFragmentManager() return (DialogFragment)
getActivity()
.getSupportFragmentManager()
.findFragmentByTag(DatePickerDialogModule.FRAGMENT_TAG); .findFragmentByTag(DatePickerDialogModule.FRAGMENT_TAG);
} }
@ -139,7 +135,8 @@ public class DatePickerDialogTestCase extends ReactAppInstrumentationTestCase {
@Override @Override
public void run() { public void run() {
((DatePickerDialog) datePickerFragment.getDialog()) ((DatePickerDialog) datePickerFragment.getDialog())
.getButton(DialogInterface.BUTTON_POSITIVE).performClick(); .getButton(DialogInterface.BUTTON_POSITIVE)
.performClick();
} }
}); });
@ -171,5 +168,4 @@ public class DatePickerDialogTestCase extends ReactAppInstrumentationTestCase {
assertEquals(0, mRecordingModule.getDates().size()); assertEquals(0, mRecordingModule.getDates().size());
assertEquals(1, mRecordingModule.getDismissed()); assertEquals(1, mRecordingModule.getDismissed());
} }
} }

Просмотреть файл

@ -1,20 +1,16 @@
/** /**
* Copyright (c) Facebook, Inc. and its affiliates. * Copyright (c) Facebook, Inc. and its affiliates.
* *
* This source code is licensed under the MIT license found in the * <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* LICENSE file in the root directory of this source tree. * directory of this source tree.
*/ */
package com.facebook.react.tests; package com.facebook.react.tests;
import android.view.View;
import com.facebook.react.testing.ReactAppInstrumentationTestCase; import com.facebook.react.testing.ReactAppInstrumentationTestCase;
import com.facebook.react.testing.ReactInstanceSpecForTest; import com.facebook.react.testing.ReactInstanceSpecForTest;
import com.facebook.react.testing.StringRecordingModule; import com.facebook.react.testing.StringRecordingModule;
/** /** Simple test case to check that onError does not get called with undefined */
* Simple test case to check that onError does not get called with undefined
*/
public class ImageErrorTestCase extends ReactAppInstrumentationTestCase { public class ImageErrorTestCase extends ReactAppInstrumentationTestCase {
private StringRecordingModule mStringRecordingModule; private StringRecordingModule mStringRecordingModule;
@ -32,15 +28,19 @@ public class ImageErrorTestCase extends ReactAppInstrumentationTestCase {
Thread.sleep(3000); Thread.sleep(3000);
assertEquals(3, mStringRecordingModule.getCalls().size()); assertEquals(3, mStringRecordingModule.getCalls().size());
assertEquals("Got error: Unsupported uri scheme! Uri is: ", mStringRecordingModule.getCalls().get(0)); assertEquals(
assertEquals("Got error: /does/not/exist: open failed: ENOENT (No such file or directory)", mStringRecordingModule.getCalls().get(1)); "Got error: Unsupported uri scheme! Uri is: ", mStringRecordingModule.getCalls().get(0));
assertEquals("Got error: Unexpected HTTP code Response{protocol=http/1.1, code=404, message=Not Found, url=https://typo_error_facebook.github.io/react/logo-og.png}", mStringRecordingModule.getCalls().get(2)); assertEquals(
"Got error: /does/not/exist: open failed: ENOENT (No such file or directory)",
mStringRecordingModule.getCalls().get(1));
assertEquals(
"Got error: Unexpected HTTP code Response{protocol=http/1.1, code=404, message=Not Found, url=https://typo_error_facebook.github.io/react/logo-og.png}",
mStringRecordingModule.getCalls().get(2));
} }
@Override @Override
protected ReactInstanceSpecForTest createReactInstanceSpecForTest() { protected ReactInstanceSpecForTest createReactInstanceSpecForTest() {
mStringRecordingModule = new StringRecordingModule(); mStringRecordingModule = new StringRecordingModule();
return super.createReactInstanceSpecForTest() return super.createReactInstanceSpecForTest().addNativeModule(mStringRecordingModule);
.addNativeModule(mStringRecordingModule);
} }
} }

Просмотреть файл

@ -1,18 +1,15 @@
/** /**
* Copyright (c) 2014-present, Facebook, Inc. * Copyright (c) 2014-present, Facebook, Inc.
* *
* This source code is licensed under the MIT license found in the * <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* LICENSE file in the root directory of this source tree. * directory of this source tree.
*/ */
package com.facebook.react.tests; package com.facebook.react.tests;
import android.view.View; import android.view.View;
import com.facebook.react.testing.ReactAppInstrumentationTestCase; import com.facebook.react.testing.ReactAppInstrumentationTestCase;
/** /** Simple test case for passing overlayColor prop to the Image component */
* Simple test case for passing overlayColor prop to the Image component
*/
public class ImageOverlayColorTestCase extends ReactAppInstrumentationTestCase { public class ImageOverlayColorTestCase extends ReactAppInstrumentationTestCase {
@Override @Override

Просмотреть файл

@ -1,28 +1,23 @@
/** /**
* Copyright (c) Facebook, Inc. and its affiliates. * Copyright (c) Facebook, Inc. and its affiliates.
* *
* This source code is licensed under the MIT license found in the * <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* LICENSE file in the root directory of this source tree. * directory of this source tree.
*/ */
package com.facebook.react.tests; package com.facebook.react.tests;
import android.os.Bundle; import android.os.Bundle;
import android.test.ActivityInstrumentationTestCase2; import android.test.ActivityInstrumentationTestCase2;
import com.facebook.react.bridge.BaseJavaModule; import com.facebook.react.bridge.BaseJavaModule;
import com.facebook.react.testing.FakeWebSocketModule;
import com.facebook.react.testing.ReactInstanceSpecForTest;
import com.facebook.react.bridge.ReactMethod; import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.ReadableArray; import com.facebook.react.bridge.ReadableArray;
import com.facebook.react.bridge.ReadableMap; import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.testing.FakeWebSocketModule;
import com.facebook.react.testing.ReactAppTestActivity; import com.facebook.react.testing.ReactAppTestActivity;
import com.facebook.react.testing.ReactInstanceSpecForTest;
/** /** Simple test case for passing initial props to the root React application. */
* Simple test case for passing initial props to the root React application. public class InitialPropsTestCase extends ActivityInstrumentationTestCase2<ReactAppTestActivity> {
*/
public class InitialPropsTestCase extends
ActivityInstrumentationTestCase2<ReactAppTestActivity> {
public static final String DEFAULT_JS_BUNDLE = "AndroidTestBundle.js"; public static final String DEFAULT_JS_BUNDLE = "AndroidTestBundle.js";
@ -84,11 +79,7 @@ public class InitialPropsTestCase extends
props.putFloatArray("key9", new float[] {1.6f, 2.6f, 3.6f}); props.putFloatArray("key9", new float[] {1.6f, 2.6f, 3.6f});
props.putBooleanArray("key10", new boolean[] {true, false}); props.putBooleanArray("key10", new boolean[] {true, false});
activity.loadApp( activity.loadApp(
"InitialPropsTestApp", "InitialPropsTestApp", catalystInstanceSpec, props, DEFAULT_JS_BUNDLE, false);
catalystInstanceSpec,
props,
DEFAULT_JS_BUNDLE,
false);
} }
}); });
activity.waitForBridgeAndUIIdle(); activity.waitForBridgeAndUIIdle();

Просмотреть файл

@ -1,10 +1,9 @@
/** /**
* Copyright (c) Facebook, Inc. and its affiliates. * Copyright (c) Facebook, Inc. and its affiliates.
* *
* This source code is licensed under the MIT license found in the * <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* LICENSE file in the root directory of this source tree. * directory of this source tree.
*/ */
package com.facebook.react.tests; package com.facebook.react.tests;
import com.facebook.react.bridge.CatalystInstance; import com.facebook.react.bridge.CatalystInstance;
@ -23,13 +22,12 @@ import com.facebook.react.views.view.ReactViewManager;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
/** /** Test locale-based functionality of JS VM */
* Test locale-based functionality of JS VM
*/
public class JSLocaleTest extends ReactIntegrationTestCase { public class JSLocaleTest extends ReactIntegrationTestCase {
private interface TestJSLocaleModule extends JavaScriptModule { private interface TestJSLocaleModule extends JavaScriptModule {
void toUpper(String string); void toUpper(String string);
void toLower(String string); void toLower(String string);
} }
@ -41,12 +39,8 @@ public class JSLocaleTest extends ReactIntegrationTestCase {
protected void setUp() throws Exception { protected void setUp() throws Exception {
super.setUp(); super.setUp();
List<ViewManager> viewManagers = Arrays.<ViewManager>asList( List<ViewManager> viewManagers = Arrays.<ViewManager>asList(new ReactViewManager());
new ReactViewManager()); final UIManagerModule mUIManager = new UIManagerModule(getContext(), viewManagers, 0);
final UIManagerModule mUIManager = new UIManagerModule(
getContext(),
viewManagers,
0);
UiThreadUtil.runOnUiThread( UiThreadUtil.runOnUiThread(
new Runnable() { new Runnable() {
@Override @Override
@ -58,7 +52,8 @@ public class JSLocaleTest extends ReactIntegrationTestCase {
waitForIdleSync(); waitForIdleSync();
mStringRecordingModule = new StringRecordingModule(); mStringRecordingModule = new StringRecordingModule();
mInstance = ReactTestHelper.catalystInstanceBuilder(this) mInstance =
ReactTestHelper.catalystInstanceBuilder(this)
.addNativeModule(mStringRecordingModule) .addNativeModule(mStringRecordingModule)
.addNativeModule(mUIManager) .addNativeModule(mUIManager)
.addNativeModule(new DeviceInfoModule(getContext())) .addNativeModule(new DeviceInfoModule(getContext()))

Просмотреть файл

@ -1,25 +1,23 @@
/** /**
* Copyright (c) Facebook, Inc. and its affiliates. * Copyright (c) Facebook, Inc. and its affiliates.
* *
* This source code is licensed under the MIT license found in the * <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* LICENSE file in the root directory of this source tree. * directory of this source tree.
*/ */
package com.facebook.react.tests; package com.facebook.react.tests;
import android.widget.ScrollView; import android.widget.ScrollView;
import com.facebook.react.uimanager.PixelUtil;
import com.facebook.react.testing.ReactAppInstrumentationTestCase; import com.facebook.react.testing.ReactAppInstrumentationTestCase;
import com.facebook.react.testing.SingleTouchGestureGenerator; import com.facebook.react.testing.SingleTouchGestureGenerator;
import com.facebook.react.uimanager.PixelUtil;
/** /**
* Test case to verify that JSResponder flow work correctly. * Test case to verify that JSResponder flow work correctly.
* *
* In a single test case scenario we have a view with pan gesture recognizer containing a scrollview * <p>In a single test case scenario we have a view with pan gesture recognizer containing a
* We verify that by vertical drags affects a scrollview while horizontal drags are suppose to * scrollview We verify that by vertical drags affects a scrollview while horizontal drags are
* be recognized by pan responder and setJSResponder should be triggered resulting in scrollview * suppose to be recognized by pan responder and setJSResponder should be triggered resulting in
* events being intercepted. * scrollview events being intercepted.
*/ */
public class JSResponderTestCase extends ReactAppInstrumentationTestCase { public class JSResponderTestCase extends ReactAppInstrumentationTestCase {
@ -55,13 +53,9 @@ public class JSResponderTestCase extends ReactAppInstrumentationTestCase {
waitForBridgeAndUIIdle(); waitForBridgeAndUIIdle();
gestureGenerator gestureGenerator.dragTo(30 + inpx40dp, 30, 10, 1200).endGesture();
.dragTo(30 + inpx40dp, 30, 10, 1200)
.endGesture();
waitForBridgeAndUIIdle(); waitForBridgeAndUIIdle();
assertEquals("Expected not to scroll", scrollView.getScrollY(), previousScroll); assertEquals("Expected not to scroll", scrollView.getScrollY(), previousScroll);
} }
} }

Просмотреть файл

@ -1,19 +1,16 @@
/** /**
* Copyright (c) Facebook, Inc. and its affiliates. * Copyright (c) Facebook, Inc. and its affiliates.
* *
* This source code is licensed under the MIT license found in the * <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* LICENSE file in the root directory of this source tree. * directory of this source tree.
*/ */
package com.facebook.react.tests; package com.facebook.react.tests;
import com.facebook.react.testing.ReactAppInstrumentationTestCase; import com.facebook.react.testing.ReactAppInstrumentationTestCase;
import com.facebook.react.testing.ReactInstanceSpecForTest; import com.facebook.react.testing.ReactInstanceSpecForTest;
import com.facebook.react.testing.StringRecordingModule; import com.facebook.react.testing.StringRecordingModule;
/** /** Simple test to verify that layout events (onLayout) propagate to JS from native. */
* Simple test to verify that layout events (onLayout) propagate to JS from native.
*/
public class LayoutEventsTestCase extends ReactAppInstrumentationTestCase { public class LayoutEventsTestCase extends ReactAppInstrumentationTestCase {
private StringRecordingModule mStringRecordingModule; private StringRecordingModule mStringRecordingModule;
@ -23,9 +20,7 @@ public class LayoutEventsTestCase extends ReactAppInstrumentationTestCase {
return "LayoutEventsTestApp"; return "LayoutEventsTestApp";
} }
/** /** Creates a UI in JS and verifies the onLayout handler is called. */
* Creates a UI in JS and verifies the onLayout handler is called.
*/
public void testOnLayoutCalled() { public void testOnLayoutCalled() {
assertEquals(3, mStringRecordingModule.getCalls().size()); assertEquals(3, mStringRecordingModule.getCalls().size());
assertEquals("10,10-100x100", mStringRecordingModule.getCalls().get(0)); assertEquals("10,10-100x100", mStringRecordingModule.getCalls().get(0));
@ -36,7 +31,6 @@ public class LayoutEventsTestCase extends ReactAppInstrumentationTestCase {
@Override @Override
protected ReactInstanceSpecForTest createReactInstanceSpecForTest() { protected ReactInstanceSpecForTest createReactInstanceSpecForTest() {
mStringRecordingModule = new StringRecordingModule(); mStringRecordingModule = new StringRecordingModule();
return super.createReactInstanceSpecForTest() return super.createReactInstanceSpecForTest().addNativeModule(mStringRecordingModule);
.addNativeModule(mStringRecordingModule);
} }
} }

Просмотреть файл

@ -1,23 +1,20 @@
/** /**
* Copyright (c) Facebook, Inc. and its affiliates. * Copyright (c) Facebook, Inc. and its affiliates.
* *
* This source code is licensed under the MIT license found in the * <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* LICENSE file in the root directory of this source tree. * directory of this source tree.
*/ */
package com.facebook.react.tests; package com.facebook.react.tests;
import android.view.View;
import com.facebook.react.testing.ReactAppInstrumentationTestCase;
import com.facebook.react.uimanager.util.ReactFindViewUtil;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
import android.view.View;
import com.facebook.react.testing.ReactAppInstrumentationTestCase;
import com.facebook.react.uimanager.util.ReactFindViewUtil;
/** /**
* Tests that the 'nativeID' property can be set on various views. * Tests that the 'nativeID' property can be set on various views. The 'nativeID' property is used
* The 'nativeID' property is used to reference react managed views from native code. * to reference react managed views from native code.
*/ */
public class NativeIdTestCase extends ReactAppInstrumentationTestCase { public class NativeIdTestCase extends ReactAppInstrumentationTestCase {
@ -26,7 +23,8 @@ public class NativeIdTestCase extends ReactAppInstrumentationTestCase {
return "NativeIdTestApp"; return "NativeIdTestApp";
} }
private final List<String> viewTags = Arrays.asList( private final List<String> viewTags =
Arrays.asList(
"Image", "Image",
"Text", "Text",
"TouchableBounce", "TouchableBounce",
@ -41,7 +39,8 @@ public class NativeIdTestCase extends ReactAppInstrumentationTestCase {
@Override @Override
protected void setUp() throws Exception { protected void setUp() throws Exception {
mViewFound = false; mViewFound = false;
ReactFindViewUtil.addViewListener(new ReactFindViewUtil.OnViewFoundListener() { ReactFindViewUtil.addViewListener(
new ReactFindViewUtil.OnViewFoundListener() {
@Override @Override
public String getNativeId() { public String getNativeId() {
return viewTags.get(0); return viewTags.get(0);
@ -57,9 +56,7 @@ public class NativeIdTestCase extends ReactAppInstrumentationTestCase {
public void testPropertyIsSetForViews() { public void testPropertyIsSetForViews() {
for (String nativeId : viewTags) { for (String nativeId : viewTags) {
View viewWithTag = ReactFindViewUtil.findView( View viewWithTag = ReactFindViewUtil.findView(getActivity().getRootView(), nativeId);
getActivity().getRootView(),
nativeId);
assertNotNull( assertNotNull(
"View with nativeID " + nativeId + " was not found. Check NativeIdTestModule.js.", "View with nativeID " + nativeId + " was not found. Check NativeIdTestModule.js.",
viewWithTag); viewWithTag);
@ -86,7 +83,6 @@ public class NativeIdTestCase extends ReactAppInstrumentationTestCase {
} }
}); });
assertTrue( assertTrue(
"OnViewFound callback should have successfully been invoked synchronously", "OnViewFound callback should have successfully been invoked synchronously", mViewFound);
mViewFound);
} }
} }

Просмотреть файл

@ -1,10 +1,9 @@
/** /**
* Copyright (c) Facebook, Inc. and its affiliates. * Copyright (c) Facebook, Inc. and its affiliates.
* *
* This source code is licensed under the MIT license found in the * <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* LICENSE file in the root directory of this source tree. * directory of this source tree.
*/ */
package com.facebook.react.tests; package com.facebook.react.tests;
import android.content.res.Resources; import android.content.res.Resources;
@ -32,9 +31,7 @@ import java.util.Arrays;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
/** /** Test to verify that Progress bar renders as a view of the right size */
* Test to verify that Progress bar renders as a view of the right size
*/
public class ProgressBarTestCase extends ReactIntegrationTestCase { public class ProgressBarTestCase extends ReactIntegrationTestCase {
// Has same order of progressBars in ProgressBarTestModule // Has same order of progressBars in ProgressBarTestModule
@ -63,11 +60,9 @@ public class ProgressBarTestCase extends ReactIntegrationTestCase {
protected void setUp() throws Exception { protected void setUp() throws Exception {
super.setUp(); super.setUp();
List<ViewManager> viewManagers = Arrays.<ViewManager>asList( List<ViewManager> viewManagers =
new ReactViewManager(), Arrays.<ViewManager>asList(new ReactViewManager(), new ReactProgressBarViewManager());
new ReactProgressBarViewManager()); mUIManager = new UIManagerModule(getContext(), viewManagers, 0);
mUIManager =
new UIManagerModule(getContext(), viewManagers, 0);
UiThreadUtil.runOnUiThread( UiThreadUtil.runOnUiThread(
new Runnable() { new Runnable() {
@Override @Override
@ -77,7 +72,8 @@ public class ProgressBarTestCase extends ReactIntegrationTestCase {
}); });
waitForIdleSync(); waitForIdleSync();
mInstance = ReactTestHelper.catalystInstanceBuilder(this) mInstance =
ReactTestHelper.catalystInstanceBuilder(this)
.addNativeModule(mUIManager) .addNativeModule(mUIManager)
.addNativeModule(new AndroidInfoModule(getContext())) .addNativeModule(new AndroidInfoModule(getContext()))
.addNativeModule(new DeviceInfoModule(getContext())) .addNativeModule(new DeviceInfoModule(getContext()))
@ -94,16 +90,13 @@ public class ProgressBarTestCase extends ReactIntegrationTestCase {
waitForBridgeAndUIIdle(); waitForBridgeAndUIIdle();
} }
/** /** Test that the sizes of the progressBars are setup correctly */
* Test that the sizes of the progressBars are setup correctly
*/
public void testProgressBarSizes() { public void testProgressBarSizes() {
for (String style : styleList) { for (String style : styleList) {
ProgressBar newProgressBar = ProgressBar newProgressBar = new ProgressBar(getContext(), null, styles.get(style));
new ProgressBar(getContext(), null, styles.get(style)); final int spec =
final int spec = View.MeasureSpec.makeMeasureSpec( View.MeasureSpec.makeMeasureSpec(
ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, View.MeasureSpec.UNSPECIFIED);
View.MeasureSpec.UNSPECIFIED);
newProgressBar.measure(spec, spec); newProgressBar.measure(spec, spec);
final int expectedHeight = newProgressBar.getMeasuredHeight(); final int expectedHeight = newProgressBar.getMeasuredHeight();

Просмотреть файл

@ -1,25 +1,19 @@
/** /**
* Copyright (c) Facebook, Inc. and its affiliates. * Copyright (c) Facebook, Inc. and its affiliates.
* *
* This source code is licensed under the MIT license found in the * <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* LICENSE file in the root directory of this source tree. * directory of this source tree.
*/ */
package com.facebook.react.tests; package com.facebook.react.tests;
import java.util.ArrayList;
import android.view.View; import android.view.View;
import android.widget.HorizontalScrollView; import android.widget.HorizontalScrollView;
import com.facebook.react.testing.AbstractScrollViewTestCase; import com.facebook.react.testing.AbstractScrollViewTestCase;
import com.facebook.react.testing.SingleTouchGestureGenerator; import com.facebook.react.testing.SingleTouchGestureGenerator;
import com.facebook.react.uimanager.PixelUtil; import com.facebook.react.uimanager.PixelUtil;
import java.util.ArrayList;
/** /** Integration test for horizontal ScrollView. See ScrollViewTestModule.js */
* Integration test for horizontal ScrollView.
* See ScrollViewTestModule.js
*/
public class ReactHorizontalScrollViewTestCase extends AbstractScrollViewTestCase { public class ReactHorizontalScrollViewTestCase extends AbstractScrollViewTestCase {
@Override @Override
@ -61,8 +55,7 @@ public class ReactHorizontalScrollViewTestCase extends AbstractScrollViewTestCas
assertFalse("Expected to receive at least one scroll event", xOffsets.isEmpty()); assertFalse("Expected to receive at least one scroll event", xOffsets.isEmpty());
assertTrue("Expected offset to be greater than 0", xOffsets.get(xOffsets.size() - 1) > 0); assertTrue("Expected offset to be greater than 0", xOffsets.get(xOffsets.size() - 1) > 0);
assertTrue( assertTrue(
"Expected no item click event fired", "Expected no item click event fired", mScrollListenerModule.getItemsPressed().isEmpty());
mScrollListenerModule.getItemsPressed().isEmpty());
assertEquals( assertEquals(
"Expected last offset to be offset of scroll view", "Expected last offset to be offset of scroll view",
PixelUtil.toDIPFromPixel(scrollView.getScrollX()), PixelUtil.toDIPFromPixel(scrollView.getScrollX()),
@ -103,9 +96,7 @@ public class ReactHorizontalScrollViewTestCase extends AbstractScrollViewTestCas
assertEquals(visibleItemNumber, (int) itemIds.get(0)); assertEquals(visibleItemNumber, (int) itemIds.get(0));
} }
/** /** Verify that 'scrollTo' command makes ScrollView start scrolling */
* Verify that 'scrollTo' command makes ScrollView start scrolling
*/
public void testScrollToCommand() throws Exception { public void testScrollToCommand() throws Exception {
HorizontalScrollView scrollView = getViewAtPath(0); HorizontalScrollView scrollView = getViewAtPath(0);
ScrollViewTestModule jsModule = ScrollViewTestModule jsModule =

Просмотреть файл

@ -1,29 +1,26 @@
/** /**
* Copyright (c) Facebook, Inc. and its affiliates. * Copyright (c) Facebook, Inc. and its affiliates.
* *
* This source code is licensed under the MIT license found in the * <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* LICENSE file in the root directory of this source tree. * directory of this source tree.
*/ */
package com.facebook.react.tests; package com.facebook.react.tests;
import java.util.ArrayList;
import java.util.List;
import android.graphics.Color; import android.graphics.Color;
import android.widget.Spinner; import android.widget.Spinner;
import android.widget.SpinnerAdapter; import android.widget.SpinnerAdapter;
import android.widget.TextView; import android.widget.TextView;
import com.facebook.react.bridge.BaseJavaModule; import com.facebook.react.bridge.BaseJavaModule;
import com.facebook.react.testing.ReactInstanceSpecForTest;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.JavaScriptModule; import com.facebook.react.bridge.JavaScriptModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.testing.ReactAppInstrumentationTestCase;
import com.facebook.react.testing.ReactInstanceSpecForTest;
import com.facebook.react.views.picker.ReactDialogPickerManager; import com.facebook.react.views.picker.ReactDialogPickerManager;
import com.facebook.react.views.picker.ReactDropdownPickerManager; import com.facebook.react.views.picker.ReactDropdownPickerManager;
import com.facebook.react.views.picker.ReactPicker; import com.facebook.react.views.picker.ReactPicker;
import com.facebook.react.views.picker.ReactPickerManager; import com.facebook.react.views.picker.ReactPickerManager;
import com.facebook.react.testing.ReactAppInstrumentationTestCase; import java.util.ArrayList;
import java.util.List;
/** /**
* Integration test for {@link ReactDialogPickerManager} and {@link ReactDropdownPickerManager} * Integration test for {@link ReactDialogPickerManager} and {@link ReactDropdownPickerManager}
@ -34,7 +31,9 @@ public class ReactPickerTestCase extends ReactAppInstrumentationTestCase {
private static interface PickerAndroidTestModule extends JavaScriptModule { private static interface PickerAndroidTestModule extends JavaScriptModule {
public void selectItem(int position); public void selectItem(int position);
public void setMode(String mode); public void setMode(String mode);
public void setPrimaryColor(String color); public void setPrimaryColor(String color);
} }
@ -66,8 +65,7 @@ public class ReactPickerTestCase extends ReactAppInstrumentationTestCase {
@Override @Override
protected ReactInstanceSpecForTest createReactInstanceSpecForTest() { protected ReactInstanceSpecForTest createReactInstanceSpecForTest() {
mRecordingModule = new PickerAndroidRecordingModule(); mRecordingModule = new PickerAndroidRecordingModule();
return super.createReactInstanceSpecForTest() return super.createReactInstanceSpecForTest().addNativeModule(mRecordingModule);
.addNativeModule(mRecordingModule);
} }
public void testBasicProperties() { public void testBasicProperties() {
@ -88,29 +86,22 @@ public class ReactPickerTestCase extends ReactAppInstrumentationTestCase {
assertEquals(Color.GREEN, ((TextView) adapter.getView(1, null, null)).getCurrentTextColor()); assertEquals(Color.GREEN, ((TextView) adapter.getView(1, null, null)).getCurrentTextColor());
assertEquals(Color.BLUE, ((TextView) adapter.getView(2, null, null)).getCurrentTextColor()); assertEquals(Color.BLUE, ((TextView) adapter.getView(2, null, null)).getCurrentTextColor());
assertEquals( assertEquals(
Color.RED, Color.RED, ((TextView) adapter.getDropDownView(0, null, null)).getCurrentTextColor());
((TextView) adapter.getDropDownView(0, null, null)).getCurrentTextColor());
assertEquals( assertEquals(
Color.GREEN, Color.GREEN, ((TextView) adapter.getDropDownView(1, null, null)).getCurrentTextColor());
((TextView) adapter.getDropDownView(1, null, null)).getCurrentTextColor());
assertEquals( assertEquals(
Color.BLUE, Color.BLUE, ((TextView) adapter.getDropDownView(2, null, null)).getCurrentTextColor());
((TextView) adapter.getDropDownView(2, null, null)).getCurrentTextColor());
getTestModule().setPrimaryColor("black"); getTestModule().setPrimaryColor("black");
waitForBridgeAndUIIdle(); waitForBridgeAndUIIdle();
assertEquals(Color.BLACK, ((TextView) adapter.getView(0, null, null)).getCurrentTextColor()); assertEquals(Color.BLACK, ((TextView) adapter.getView(0, null, null)).getCurrentTextColor());
assertEquals(Color.BLACK, ((TextView) adapter.getView(1, null, null)).getCurrentTextColor()); assertEquals(Color.BLACK, ((TextView) adapter.getView(1, null, null)).getCurrentTextColor());
assertEquals(Color.BLACK, ((TextView) adapter.getView(2, null, null)).getCurrentTextColor()); assertEquals(Color.BLACK, ((TextView) adapter.getView(2, null, null)).getCurrentTextColor());
assertEquals( assertEquals(
Color.RED, Color.RED, ((TextView) adapter.getDropDownView(0, null, null)).getCurrentTextColor());
((TextView) adapter.getDropDownView(0, null, null)).getCurrentTextColor());
assertEquals( assertEquals(
Color.GREEN, Color.GREEN, ((TextView) adapter.getDropDownView(1, null, null)).getCurrentTextColor());
((TextView) adapter.getDropDownView(1, null, null)).getCurrentTextColor());
assertEquals( assertEquals(
Color.BLUE, Color.BLUE, ((TextView) adapter.getDropDownView(2, null, null)).getCurrentTextColor());
((TextView) adapter.getDropDownView(2, null, null)).getCurrentTextColor());
} }
public void testDropdownPicker() { public void testDropdownPicker() {
@ -176,9 +167,8 @@ public class ReactPickerTestCase extends ReactAppInstrumentationTestCase {
updateFirstSpinnerAndCheckLastSpinnerMatches(2); updateFirstSpinnerAndCheckLastSpinnerMatches(2);
} }
private void updateFirstSpinnerAndCheckLastSpinnerMatches( private void updateFirstSpinnerAndCheckLastSpinnerMatches(final int indexToSelect)
final int indexToSelect throws Throwable {
) throws Throwable {
// The last spinner has the same selected value as the first one. // The last spinner has the same selected value as the first one.
// Test that user selection is propagated correctly to JS, to setState, and to Spinners. // Test that user selection is propagated correctly to JS, to setState, and to Spinners.
runTestOnUiThread( runTestOnUiThread(
@ -202,5 +192,4 @@ public class ReactPickerTestCase extends ReactAppInstrumentationTestCase {
private PickerAndroidTestModule getTestModule() { private PickerAndroidTestModule getTestModule() {
return getReactContext().getCatalystInstance().getJSModule(PickerAndroidTestModule.class); return getReactContext().getCatalystInstance().getJSModule(PickerAndroidTestModule.class);
} }
} }

Просмотреть файл

@ -1,25 +1,19 @@
/** /**
* Copyright (c) Facebook, Inc. and its affiliates. * Copyright (c) Facebook, Inc. and its affiliates.
* *
* This source code is licensed under the MIT license found in the * <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* LICENSE file in the root directory of this source tree. * directory of this source tree.
*/ */
package com.facebook.react.tests; package com.facebook.react.tests;
import java.util.ArrayList;
import android.view.View; import android.view.View;
import android.widget.ScrollView; import android.widget.ScrollView;
import com.facebook.react.testing.AbstractScrollViewTestCase; import com.facebook.react.testing.AbstractScrollViewTestCase;
import com.facebook.react.testing.SingleTouchGestureGenerator; import com.facebook.react.testing.SingleTouchGestureGenerator;
import com.facebook.react.uimanager.PixelUtil; import com.facebook.react.uimanager.PixelUtil;
import java.util.ArrayList;
/** /** Integration test for vertical ScrollView. See ScrollViewTestModule.js */
* Integration test for vertical ScrollView.
* See ScrollViewTestModule.js
*/
public class ReactScrollViewTestCase extends AbstractScrollViewTestCase { public class ReactScrollViewTestCase extends AbstractScrollViewTestCase {
@Override @Override
@ -61,8 +55,7 @@ public class ReactScrollViewTestCase extends AbstractScrollViewTestCase {
assertFalse("Expected to receive at least one scroll event", yOffsets.isEmpty()); assertFalse("Expected to receive at least one scroll event", yOffsets.isEmpty());
assertTrue("Expected offset to be greater than 0", yOffsets.get(yOffsets.size() - 1) > 0); assertTrue("Expected offset to be greater than 0", yOffsets.get(yOffsets.size() - 1) > 0);
assertTrue( assertTrue(
"Expected no item click event fired", "Expected no item click event fired", mScrollListenerModule.getItemsPressed().isEmpty());
mScrollListenerModule.getItemsPressed().isEmpty());
assertEquals( assertEquals(
"Expected last offset to be offset of scroll view", "Expected last offset to be offset of scroll view",
PixelUtil.toDIPFromPixel(scrollView.getScrollY()), PixelUtil.toDIPFromPixel(scrollView.getScrollY()),
@ -104,9 +97,7 @@ public class ReactScrollViewTestCase extends AbstractScrollViewTestCase {
assertEquals(visibleItemNumber, (int) itemIds.get(0)); assertEquals(visibleItemNumber, (int) itemIds.get(0));
} }
/** /** Verify that 'scrollTo' command makes ScrollView start scrolling */
* Verify that 'scrollTo' command makes ScrollView start scrolling
*/
public void testScrollToCommand() throws Exception { public void testScrollToCommand() throws Exception {
ScrollView scrollView = getViewAtPath(0); ScrollView scrollView = getViewAtPath(0);
ScrollViewTestModule jsModule = ScrollViewTestModule jsModule =

Просмотреть файл

@ -1,24 +1,20 @@
/** /**
* Copyright (c) Facebook, Inc. and its affiliates. * Copyright (c) Facebook, Inc. and its affiliates.
* *
* This source code is licensed under the MIT license found in the * <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* LICENSE file in the root directory of this source tree. * directory of this source tree.
*/ */
package com.facebook.react.tests; package com.facebook.react.tests;
import android.view.View; import android.view.View;
import com.facebook.react.testing.ReactAppInstrumentationTestCase;
import com.facebook.react.testing.ReactInstanceSpecForTest;
import com.facebook.react.bridge.BaseJavaModule; import com.facebook.react.bridge.BaseJavaModule;
import com.facebook.react.bridge.JavaScriptModule; import com.facebook.react.bridge.JavaScriptModule;
import com.facebook.react.bridge.ReactMethod; import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.testing.ReactAppInstrumentationTestCase;
import com.facebook.react.testing.ReactInstanceSpecForTest;
import com.facebook.react.views.swiperefresh.ReactSwipeRefreshLayout; import com.facebook.react.views.swiperefresh.ReactSwipeRefreshLayout;
/** /** Test case for {@link ReactSwipeRefreshLayout}. */
* Test case for {@link ReactSwipeRefreshLayout}.
*/
public class ReactSwipeRefreshLayoutTestCase extends ReactAppInstrumentationTestCase { public class ReactSwipeRefreshLayoutTestCase extends ReactAppInstrumentationTestCase {
private class SwipeRefreshLayoutRecordingModule extends BaseJavaModule { private class SwipeRefreshLayoutRecordingModule extends BaseJavaModule {
@ -53,8 +49,7 @@ public class ReactSwipeRefreshLayoutTestCase extends ReactAppInstrumentationTest
@Override @Override
protected ReactInstanceSpecForTest createReactInstanceSpecForTest() { protected ReactInstanceSpecForTest createReactInstanceSpecForTest() {
return super.createReactInstanceSpecForTest() return super.createReactInstanceSpecForTest().addNativeModule(mRecordingModule);
.addNativeModule(mRecordingModule);
} }
public void testRefreshNoScroll() { public void testRefreshNoScroll() {
@ -98,5 +93,4 @@ public class ReactSwipeRefreshLayoutTestCase extends ReactAppInstrumentationTest
waitForBridgeAndUIIdle(); waitForBridgeAndUIIdle();
assertEquals(0, mRecordingModule.getCount()); assertEquals(0, mRecordingModule.getCount());
} }
} }

Просмотреть файл

@ -1,36 +1,24 @@
/** /**
* Copyright (c) Facebook, Inc. and its affiliates. * Copyright (c) Facebook, Inc. and its affiliates.
* *
* This source code is licensed under the MIT license found in the * <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* LICENSE file in the root directory of this source tree. * directory of this source tree.
*/ */
package com.facebook.react.tests; package com.facebook.react.tests;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Instrumentation.ActivityMonitor; import android.app.Instrumentation.ActivityMonitor;
import android.content.DialogInterface;
import android.content.Intent; import android.content.Intent;
import android.content.IntentFilter; import android.content.IntentFilter;
import android.content.IntentFilter.MalformedMimeTypeException;
import androidx.fragment.app.DialogFragment;
import com.facebook.react.bridge.BaseJavaModule; import com.facebook.react.bridge.BaseJavaModule;
import com.facebook.react.testing.ReactInstanceSpecForTest;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.JavaScriptModule; import com.facebook.react.bridge.JavaScriptModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.WritableMap; import com.facebook.react.bridge.WritableMap;
import com.facebook.react.bridge.WritableNativeMap; import com.facebook.react.bridge.WritableNativeMap;
import com.facebook.react.modules.share.ShareModule; import com.facebook.react.modules.share.ShareModule;
import com.facebook.react.testing.ReactAppInstrumentationTestCase; import com.facebook.react.testing.ReactAppInstrumentationTestCase;
import com.facebook.react.testing.ReactInstanceSpecForTest;
/** /** Test case for {@link ShareModule}. */
* Test case for {@link ShareModule}.
*/
public class ShareTestCase extends ReactAppInstrumentationTestCase { public class ShareTestCase extends ReactAppInstrumentationTestCase {
private static interface ShareTestModule extends JavaScriptModule { private static interface ShareTestModule extends JavaScriptModule {
@ -64,15 +52,13 @@ public class ShareTestCase extends ReactAppInstrumentationTestCase {
public int getErrors() { public int getErrors() {
return mErrors; return mErrors;
} }
} }
final ShareRecordingModule mRecordingModule = new ShareRecordingModule(); final ShareRecordingModule mRecordingModule = new ShareRecordingModule();
@Override @Override
protected ReactInstanceSpecForTest createReactInstanceSpecForTest() { protected ReactInstanceSpecForTest createReactInstanceSpecForTest() {
return super.createReactInstanceSpecForTest() return super.createReactInstanceSpecForTest().addNativeModule(mRecordingModule);
.addNativeModule(mRecordingModule);
} }
@Override @Override
@ -101,7 +87,5 @@ public class ShareTestCase extends ReactAppInstrumentationTestCase {
assertEquals(1, monitor.getHits()); assertEquals(1, monitor.getHits());
assertEquals(1, mRecordingModule.getOpened()); assertEquals(1, mRecordingModule.getOpened());
assertEquals(0, mRecordingModule.getErrors()); assertEquals(0, mRecordingModule.getErrors());
} }
} }

Просмотреть файл

@ -1,25 +1,20 @@
/** /**
* Copyright (c) Facebook, Inc. and its affiliates. * Copyright (c) Facebook, Inc. and its affiliates.
* *
* This source code is licensed under the MIT license found in the * <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* LICENSE file in the root directory of this source tree. * directory of this source tree.
*/ */
package com.facebook.react.tests; package com.facebook.react.tests;
import android.view.View;
import com.facebook.react.testing.ReactAppInstrumentationTestCase;
import com.facebook.react.testing.ReactTestHelper;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
import android.view.View;
import com.facebook.react.views.picker.ReactDropdownPickerManager;
import com.facebook.react.testing.ReactAppInstrumentationTestCase;
import com.facebook.react.testing.ReactInstanceSpecForTest;
import com.facebook.react.testing.ReactTestHelper;
/** /**
* Tests that the 'testID' property can be set on various views. * Tests that the 'testID' property can be set on various views. The 'testID' property is used to
* The 'testID' property is used to locate views in UI tests. * locate views in UI tests.
*/ */
public class TestIdTestCase extends ReactAppInstrumentationTestCase { public class TestIdTestCase extends ReactAppInstrumentationTestCase {
@ -28,7 +23,8 @@ public class TestIdTestCase extends ReactAppInstrumentationTestCase {
return "TestIdTestApp"; return "TestIdTestApp";
} }
private final List<String> viewTags = Arrays.asList( private final List<String> viewTags =
Arrays.asList(
"Image", "Image",
"Text", "Text",
"TouchableBounce", "TouchableBounce",
@ -36,14 +32,11 @@ public class TestIdTestCase extends ReactAppInstrumentationTestCase {
"TouchableOpacity", "TouchableOpacity",
"TouchableWithoutFeedback", "TouchableWithoutFeedback",
"TextInput", "TextInput",
"View" "View");
);
public void testPropertyIsSetForViews() { public void testPropertyIsSetForViews() {
for (String tag : viewTags) { for (String tag : viewTags) {
View viewWithTag = ReactTestHelper.getViewWithReactTestId( View viewWithTag = ReactTestHelper.getViewWithReactTestId(getActivity().getRootView(), tag);
getActivity().getRootView(),
tag);
assertNotNull( assertNotNull(
"View with testID tag " + tag + " was not found. Check TestIdTestModule.js.", "View with testID tag " + tag + " was not found. Check TestIdTestModule.js.",
viewWithTag); viewWithTag);

Просмотреть файл

@ -1,21 +1,18 @@
/** /**
* Copyright (c) Facebook, Inc. and its affiliates. * Copyright (c) Facebook, Inc. and its affiliates.
* *
* This source code is licensed under the MIT license found in the * <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* LICENSE file in the root directory of this source tree. * directory of this source tree.
*/ */
package com.facebook.react.tests; package com.facebook.react.tests;
import android.graphics.Color; import android.graphics.Color;
import android.text.style.ForegroundColorSpan; import android.text.style.ForegroundColorSpan;
import android.util.TypedValue; import android.util.TypedValue;
import android.view.KeyEvent;
import android.view.View; import android.view.View;
import android.view.ViewGroup; import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo; import android.view.inputmethod.EditorInfo;
import android.widget.EditText; import android.widget.EditText;
import com.facebook.react.bridge.JavaScriptModule; import com.facebook.react.bridge.JavaScriptModule;
import com.facebook.react.testing.ReactAppInstrumentationTestCase; import com.facebook.react.testing.ReactAppInstrumentationTestCase;
import com.facebook.react.testing.ReactInstanceSpecForTest; import com.facebook.react.testing.ReactInstanceSpecForTest;
@ -23,9 +20,7 @@ import com.facebook.react.testing.StringRecordingModule;
import com.facebook.react.uimanager.PixelUtil; import com.facebook.react.uimanager.PixelUtil;
import com.facebook.react.views.textinput.ReactEditText; import com.facebook.react.views.textinput.ReactEditText;
/** /** Test to verify that TextInput renders correctly */
* Test to verify that TextInput renders correctly
*/
public class TextInputTestCase extends ReactAppInstrumentationTestCase { public class TextInputTestCase extends ReactAppInstrumentationTestCase {
private final StringRecordingModule mRecordingModule = new StringRecordingModule(); private final StringRecordingModule mRecordingModule = new StringRecordingModule();
@ -47,20 +42,17 @@ public class TextInputTestCase extends ReactAppInstrumentationTestCase {
EditText editText = new EditText(textInputViewNoHeight.getContext()); EditText editText = new EditText(textInputViewNoHeight.getContext());
editText.setTextSize( editText.setTextSize(
TypedValue.COMPLEX_UNIT_PX, TypedValue.COMPLEX_UNIT_PX, (float) Math.ceil(PixelUtil.toPixelFromSP(21.f)));
(float) Math.ceil(PixelUtil.toPixelFromSP(21.f)));
editText.setPadding(0, 0, 0, 0); editText.setPadding(0, 0, 0, 0);
int measureSpec = View.MeasureSpec.makeMeasureSpec( int measureSpec =
ViewGroup.LayoutParams.WRAP_CONTENT, View.MeasureSpec.makeMeasureSpec(
View.MeasureSpec.UNSPECIFIED); ViewGroup.LayoutParams.WRAP_CONTENT, View.MeasureSpec.UNSPECIFIED);
editText.measure(measureSpec, measureSpec); editText.measure(measureSpec, measureSpec);
assertEquals(editText.getMeasuredHeight(), textInputViewNoHeight.getHeight()); assertEquals(editText.getMeasuredHeight(), textInputViewNoHeight.getHeight());
} }
/** /** Test that the cursor moves to the end of the word. */
* Test that the cursor moves to the end of the word.
*/
public void testTextInputCursorPosition() throws Throwable { public void testTextInputCursorPosition() throws Throwable {
final EditText textInputWithText = getViewByTestId("textInput3"); final EditText textInputWithText = getViewByTestId("textInput3");
@ -71,7 +63,8 @@ public class TextInputTestCase extends ReactAppInstrumentationTestCase {
textInputWithText.setSelection(3); textInputWithText.setSelection(3);
} }
}); });
getReactContext().getJSModule(TextInputTestModule.class) getReactContext()
.getJSModule(TextInputTestModule.class)
.setValueRef("textInput3", "Some other value"); .setValueRef("textInput3", "Some other value");
waitForBridgeAndUIIdle(); waitForBridgeAndUIIdle();
@ -79,9 +72,7 @@ public class TextInputTestCase extends ReactAppInstrumentationTestCase {
assertEquals(4, textInputWithText.getSelectionEnd()); assertEquals(4, textInputWithText.getSelectionEnd());
} }
/** /** Test that the colors are applied to new text */
* Test that the colors are applied to new text
*/
public void testTextInputColors() throws Throwable { public void testTextInputColors() throws Throwable {
String testIDs[] = new String[] {"textInput4", "textInput5", "textInput6"}; String testIDs[] = new String[] {"textInput4", "textInput5", "textInput6"};
@ -94,7 +85,9 @@ public class TextInputTestCase extends ReactAppInstrumentationTestCase {
ReactEditText reactEditText = getViewByTestId(testID); ReactEditText reactEditText = getViewByTestId(testID);
assertEquals( assertEquals(
Color.GREEN, Color.GREEN,
reactEditText.getText().getSpans(0, 1, ForegroundColorSpan.class)[0] reactEditText
.getText()
.getSpans(0, 1, ForegroundColorSpan.class)[0]
.getForegroundColor()); .getForegroundColor());
} }
} }
@ -113,15 +106,15 @@ public class TextInputTestCase extends ReactAppInstrumentationTestCase {
fireEditorActionAndCheckRecording(reactEditText, EditorInfo.IME_ACTION_NONE); fireEditorActionAndCheckRecording(reactEditText, EditorInfo.IME_ACTION_NONE);
} }
private void fireEditorActionAndCheckRecording(final ReactEditText reactEditText, private void fireEditorActionAndCheckRecording(
final int actionId) throws Throwable { final ReactEditText reactEditText, final int actionId) throws Throwable {
fireEditorActionAndCheckRecording(reactEditText, actionId, true); fireEditorActionAndCheckRecording(reactEditText, actionId, true);
fireEditorActionAndCheckRecording(reactEditText, actionId, false); fireEditorActionAndCheckRecording(reactEditText, actionId, false);
} }
private void fireEditorActionAndCheckRecording(final ReactEditText reactEditText, private void fireEditorActionAndCheckRecording(
final int actionId, final ReactEditText reactEditText, final int actionId, final boolean blurOnSubmit)
final boolean blurOnSubmit) throws Throwable { throws Throwable {
mRecordingModule.reset(); mRecordingModule.reset();
runTestOnUiThread( runTestOnUiThread(
@ -140,114 +133,68 @@ public class TextInputTestCase extends ReactAppInstrumentationTestCase {
} }
/** /**
* Test that the mentions input has colors displayed correctly. * Test that the mentions input has colors displayed correctly. Removed for being flaky in open
* Removed for being flaky in open source, December 2016 * source, December 2016 public void testMetionsInputColors() throws Throwable { EventDispatcher
public void testMetionsInputColors() throws Throwable { * eventDispatcher =
EventDispatcher eventDispatcher = * getReactContext().getNativeModule(UIManagerModule.class).getEventDispatcher(); ReactEditText
getReactContext().getNativeModule(UIManagerModule.class).getEventDispatcher(); * reactEditText = getViewByTestId("tokenizedInput"); String newText = "#Things and more #things";
ReactEditText reactEditText = getViewByTestId("tokenizedInput"); * int contentWidth = reactEditText.getWidth(); int contentHeight = reactEditText.getHeight(); int
String newText = "#Things and more #things"; * start = 0; int count = newText.length();
int contentWidth = reactEditText.getWidth(); *
int contentHeight = reactEditText.getHeight(); * <p>eventDispatcher.dispatchEvent( new ReactTextChangedEvent( reactEditText.getId(),
int start = 0; * newText.toString(), (int) PixelUtil.toDIPFromPixel(contentWidth), (int)
int count = newText.length(); * PixelUtil.toDIPFromPixel(contentHeight), reactEditText.incrementAndGetEventCounter()));
*
eventDispatcher.dispatchEvent( * <p>eventDispatcher.dispatchEvent( new ReactTextInputEvent( reactEditText.getId(),
new ReactTextChangedEvent( * newText.toString(), "", start, start + count - 1)); waitForBridgeAndUIIdle();
reactEditText.getId(), *
newText.toString(), * <p>ForegroundColorSpan[] spans = reactEditText .getText().getSpans(0,
(int) PixelUtil.toDIPFromPixel(contentWidth), * reactEditText.getText().length(), ForegroundColorSpan.class); assertEquals(2, spans.length);
(int) PixelUtil.toDIPFromPixel(contentHeight), * assertEquals(spans[0].getForegroundColor(), spans[1].getForegroundColor()); assertEquals(0,
reactEditText.incrementAndGetEventCounter())); * reactEditText.getText().getSpanStart(spans[1])); assertEquals(7,
* reactEditText.getText().getSpanEnd(spans[1])); assertEquals(newText.length() - 7,
eventDispatcher.dispatchEvent( * reactEditText.getText().getSpanStart(spans[0])); assertEquals(newText.length(),
new ReactTextInputEvent( * reactEditText.getText().getSpanEnd(spans[0]));
reactEditText.getId(), *
newText.toString(), * <p>String moreText = "andsuch "; String previousText = newText; newText += moreText; count =
"", * moreText.length(); start = previousText.length();
start, *
start + count - 1)); * <p>eventDispatcher.dispatchEvent( new ReactTextChangedEvent( reactEditText.getId(),
waitForBridgeAndUIIdle(); * newText.toString(), (int) PixelUtil.toDIPFromPixel(contentWidth), (int)
* PixelUtil.toDIPFromPixel(contentHeight), reactEditText.incrementAndGetEventCounter()));
ForegroundColorSpan[] spans = reactEditText *
.getText().getSpans(0, reactEditText.getText().length(), ForegroundColorSpan.class); * <p>eventDispatcher.dispatchEvent( new ReactTextInputEvent( reactEditText.getId(), moreText, "",
assertEquals(2, spans.length); * start, start + count - 1)); waitForBridgeAndUIIdle();
assertEquals(spans[0].getForegroundColor(), spans[1].getForegroundColor()); *
assertEquals(0, reactEditText.getText().getSpanStart(spans[1])); * <p>spans = reactEditText.getText() .getSpans(0, reactEditText.getText().length(),
assertEquals(7, reactEditText.getText().getSpanEnd(spans[1])); * ForegroundColorSpan.class); assertEquals(2, spans.length);
assertEquals(newText.length() - 7, reactEditText.getText().getSpanStart(spans[0])); * assertEquals(spans[0].getForegroundColor(), spans[1].getForegroundColor()); assertEquals(0,
assertEquals(newText.length(), reactEditText.getText().getSpanEnd(spans[0])); * reactEditText.getText().getSpanStart(spans[1])); assertEquals(7,
* reactEditText.getText().getSpanEnd(spans[1])); assertEquals(newText.length() - 15,
String moreText = "andsuch "; * reactEditText.getText().getSpanStart(spans[0])); assertEquals(newText.length() - 1,
String previousText = newText; * reactEditText.getText().getSpanEnd(spans[0]));
newText += moreText; *
count = moreText.length(); * <p>moreText = "morethings"; previousText = newText; newText += moreText; count =
start = previousText.length(); * moreText.length(); start = previousText.length();
*
eventDispatcher.dispatchEvent( * <p>eventDispatcher.dispatchEvent( new ReactTextChangedEvent( reactEditText.getId(),
new ReactTextChangedEvent( * newText.toString(), (int) PixelUtil.toDIPFromPixel(contentWidth), (int)
reactEditText.getId(), * PixelUtil.toDIPFromPixel(contentHeight), reactEditText.incrementAndGetEventCounter()));
newText.toString(), *
(int) PixelUtil.toDIPFromPixel(contentWidth), * <p>eventDispatcher.dispatchEvent( new ReactTextInputEvent( reactEditText.getId(), moreText, "",
(int) PixelUtil.toDIPFromPixel(contentHeight), * start, start + count - 1)); waitForBridgeAndUIIdle();
reactEditText.incrementAndGetEventCounter())); *
* <p>spans = reactEditText.getText() .getSpans(0, reactEditText.getText().length(),
eventDispatcher.dispatchEvent( * ForegroundColorSpan.class); assertEquals(spans[0].getForegroundColor(),
new ReactTextInputEvent( * spans[1].getForegroundColor()); assertEquals(2, spans.length); assertEquals(0,
reactEditText.getId(), * reactEditText.getText().getSpanStart(spans[1])); assertEquals(7,
moreText, * reactEditText.getText().getSpanEnd(spans[1])); assertEquals(newText.length() - 25,
"", * reactEditText.getText().getSpanStart(spans[0])); assertEquals(newText.length() - 11,
start, * reactEditText.getText().getSpanEnd(spans[0])); }
start + count - 1));
waitForBridgeAndUIIdle();
spans = reactEditText.getText()
.getSpans(0, reactEditText.getText().length(), ForegroundColorSpan.class);
assertEquals(2, spans.length);
assertEquals(spans[0].getForegroundColor(), spans[1].getForegroundColor());
assertEquals(0, reactEditText.getText().getSpanStart(spans[1]));
assertEquals(7, reactEditText.getText().getSpanEnd(spans[1]));
assertEquals(newText.length() - 15, reactEditText.getText().getSpanStart(spans[0]));
assertEquals(newText.length() - 1, reactEditText.getText().getSpanEnd(spans[0]));
moreText = "morethings";
previousText = newText;
newText += moreText;
count = moreText.length();
start = previousText.length();
eventDispatcher.dispatchEvent(
new ReactTextChangedEvent(
reactEditText.getId(),
newText.toString(),
(int) PixelUtil.toDIPFromPixel(contentWidth),
(int) PixelUtil.toDIPFromPixel(contentHeight),
reactEditText.incrementAndGetEventCounter()));
eventDispatcher.dispatchEvent(
new ReactTextInputEvent(
reactEditText.getId(),
moreText,
"",
start,
start + count - 1));
waitForBridgeAndUIIdle();
spans = reactEditText.getText()
.getSpans(0, reactEditText.getText().length(), ForegroundColorSpan.class);
assertEquals(spans[0].getForegroundColor(), spans[1].getForegroundColor());
assertEquals(2, spans.length);
assertEquals(0, reactEditText.getText().getSpanStart(spans[1]));
assertEquals(7, reactEditText.getText().getSpanEnd(spans[1]));
assertEquals(newText.length() - 25, reactEditText.getText().getSpanStart(spans[0]));
assertEquals(newText.length() - 11, reactEditText.getText().getSpanEnd(spans[0]));
}
*/ */
@Override @Override
protected ReactInstanceSpecForTest createReactInstanceSpecForTest() { protected ReactInstanceSpecForTest createReactInstanceSpecForTest() {
return super.createReactInstanceSpecForTest() return super.createReactInstanceSpecForTest().addNativeModule(mRecordingModule);
.addNativeModule(mRecordingModule);
} }
@Override @Override

Просмотреть файл

@ -1,31 +1,26 @@
/** /**
* Copyright (c) Facebook, Inc. and its affiliates. * Copyright (c) Facebook, Inc. and its affiliates.
* *
* This source code is licensed under the MIT license found in the * <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* LICENSE file in the root directory of this source tree. * directory of this source tree.
*/ */
package com.facebook.react.tests; package com.facebook.react.tests;
import java.util.ArrayList;
import java.util.List;
import android.app.TimePickerDialog; import android.app.TimePickerDialog;
import android.content.DialogInterface; import android.content.DialogInterface;
import androidx.fragment.app.DialogFragment; import androidx.fragment.app.DialogFragment;
import com.facebook.react.bridge.BaseJavaModule; import com.facebook.react.bridge.BaseJavaModule;
import com.facebook.react.testing.ReactInstanceSpecForTest;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.JavaScriptModule; import com.facebook.react.bridge.JavaScriptModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.WritableMap; import com.facebook.react.bridge.WritableMap;
import com.facebook.react.bridge.WritableNativeMap; import com.facebook.react.bridge.WritableNativeMap;
import com.facebook.react.modules.timepicker.TimePickerDialogModule; import com.facebook.react.modules.timepicker.TimePickerDialogModule;
import com.facebook.react.testing.ReactAppInstrumentationTestCase; import com.facebook.react.testing.ReactAppInstrumentationTestCase;
import com.facebook.react.testing.ReactInstanceSpecForTest;
import java.util.ArrayList;
import java.util.List;
/** /** Test case for {@link TimePickerDialogModule} options and callbacks. */
* Test case for {@link TimePickerDialogModule} options and callbacks.
*/
public class TimePickerDialogTestCase extends ReactAppInstrumentationTestCase { public class TimePickerDialogTestCase extends ReactAppInstrumentationTestCase {
private static interface TimePickerDialogTestModule extends JavaScriptModule { private static interface TimePickerDialogTestModule extends JavaScriptModule {
@ -75,8 +70,7 @@ public class TimePickerDialogTestCase extends ReactAppInstrumentationTestCase {
@Override @Override
protected ReactInstanceSpecForTest createReactInstanceSpecForTest() { protected ReactInstanceSpecForTest createReactInstanceSpecForTest() {
return super.createReactInstanceSpecForTest() return super.createReactInstanceSpecForTest().addNativeModule(mRecordingModule);
.addNativeModule(mRecordingModule);
} }
@Override @Override
@ -94,7 +88,9 @@ public class TimePickerDialogTestCase extends ReactAppInstrumentationTestCase {
waitForBridgeAndUIIdle(); waitForBridgeAndUIIdle();
getInstrumentation().waitForIdleSync(); getInstrumentation().waitForIdleSync();
return (DialogFragment) getActivity().getSupportFragmentManager() return (DialogFragment)
getActivity()
.getSupportFragmentManager()
.findFragmentByTag(TimePickerDialogModule.FRAGMENT_TAG); .findFragmentByTag(TimePickerDialogModule.FRAGMENT_TAG);
} }
@ -119,7 +115,8 @@ public class TimePickerDialogTestCase extends ReactAppInstrumentationTestCase {
@Override @Override
public void run() { public void run() {
((TimePickerDialog) fragment.getDialog()) ((TimePickerDialog) fragment.getDialog())
.getButton(DialogInterface.BUTTON_POSITIVE).performClick(); .getButton(DialogInterface.BUTTON_POSITIVE)
.performClick();
} }
}); });
@ -155,5 +152,4 @@ public class TimePickerDialogTestCase extends ReactAppInstrumentationTestCase {
assertEquals(0, mRecordingModule.getTimes().size()); assertEquals(0, mRecordingModule.getTimes().size());
assertEquals(1, mRecordingModule.getDismissed()); assertEquals(1, mRecordingModule.getDismissed());
} }
} }

Просмотреть файл

@ -1,10 +1,9 @@
/** /**
* Copyright (c) Facebook, Inc. and its affiliates. * Copyright (c) Facebook, Inc. and its affiliates.
* *
* This source code is licensed under the MIT license found in the * <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* LICENSE file in the root directory of this source tree. * directory of this source tree.
*/ */
package com.facebook.react.tests; package com.facebook.react.tests;
import android.graphics.Color; import android.graphics.Color;
@ -32,9 +31,13 @@ public class ViewRenderingTestCase extends ReactIntegrationTestCase {
private interface ViewRenderingTestModule extends JavaScriptModule { private interface ViewRenderingTestModule extends JavaScriptModule {
void renderViewApplication(int rootTag); void renderViewApplication(int rootTag);
void renderMarginApplication(int rootTag); void renderMarginApplication(int rootTag);
void renderBorderApplication(int rootTag); void renderBorderApplication(int rootTag);
void updateMargins(); void updateMargins();
void renderTransformApplication(int rootTag); void renderTransformApplication(int rootTag);
} }
@ -47,8 +50,7 @@ public class ViewRenderingTestCase extends ReactIntegrationTestCase {
super.setUp(); super.setUp();
List<ViewManager> viewManagers = Arrays.<ViewManager>asList(new ReactViewManager()); List<ViewManager> viewManagers = Arrays.<ViewManager>asList(new ReactViewManager());
final UIManagerModule uiManager = final UIManagerModule uiManager = new UIManagerModule(getContext(), viewManagers, 0);
new UIManagerModule(getContext(), viewManagers, 0);
UiThreadUtil.runOnUiThread( UiThreadUtil.runOnUiThread(
new Runnable() { new Runnable() {
@Override @Override
@ -58,7 +60,8 @@ public class ViewRenderingTestCase extends ReactIntegrationTestCase {
}); });
waitForIdleSync(); waitForIdleSync();
mCatalystInstance = ReactTestHelper.catalystInstanceBuilder(this) mCatalystInstance =
ReactTestHelper.catalystInstanceBuilder(this)
.addNativeModule(uiManager) .addNativeModule(uiManager)
.addNativeModule(new AndroidInfoModule(getContext())) .addNativeModule(new AndroidInfoModule(getContext()))
.addNativeModule(new DeviceInfoModule(getContext())) .addNativeModule(new DeviceInfoModule(getContext()))
@ -131,7 +134,8 @@ public class ViewRenderingTestCase extends ReactIntegrationTestCase {
} }
public void testTransformations() { public void testTransformations() {
mCatalystInstance.getJSModule(ViewRenderingTestModule.class) mCatalystInstance
.getJSModule(ViewRenderingTestModule.class)
.renderTransformApplication(mRootTag); .renderTransformApplication(mRootTag);
waitForBridgeAndUIIdle(); waitForBridgeAndUIIdle();

Просмотреть файл

@ -49,7 +49,9 @@ public class ReactInstanceManagerTest {
public void tearDown() { public void tearDown() {
final ReactRootView reactRootView = mReactRootView; final ReactRootView reactRootView = mReactRootView;
final ReactInstanceManager reactInstanceManager = mReactInstanceManager; final ReactInstanceManager reactInstanceManager = mReactInstanceManager;
InstrumentationRegistry.getInstrumentation().runOnMainSync(new Runnable() { InstrumentationRegistry.getInstrumentation()
.runOnMainSync(
new Runnable() {
@Override @Override
public void run() { public void run() {
reactRootView.unmountReactApplication(); reactRootView.unmountReactApplication();

Просмотреть файл

@ -8,34 +8,29 @@ package com.facebook.react.tests.core;
import static org.fest.assertions.api.Assertions.assertThat; import static org.fest.assertions.api.Assertions.assertThat;
import android.app.Instrumentation; import android.app.Instrumentation;
import androidx.test.InstrumentationRegistry;
import androidx.test.runner.AndroidJUnit4;
import android.util.DisplayMetrics;
import android.view.View; import android.view.View;
import android.view.ViewGroup; import android.view.ViewGroup;
import android.widget.FrameLayout; import android.widget.FrameLayout;
import androidx.test.InstrumentationRegistry;
import androidx.test.runner.AndroidJUnit4;
import com.facebook.react.ReactPackage; import com.facebook.react.ReactPackage;
import com.facebook.react.ReactRootView; import com.facebook.react.ReactRootView;
import com.facebook.react.bridge.JavaScriptModule; import com.facebook.react.bridge.JavaScriptModule;
import com.facebook.react.bridge.ModuleSpec;
import com.facebook.react.bridge.NativeModule; import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.module.annotations.ReactModule;
import com.facebook.react.module.model.ReactModuleInfo;
import com.facebook.react.module.model.ReactModuleInfoProvider;
import com.facebook.react.shell.MainReactPackage; import com.facebook.react.shell.MainReactPackage;
import com.facebook.react.testing.StringRecordingModule; import com.facebook.react.testing.StringRecordingModule;
import com.facebook.react.testing.rule.ReactNativeTestRule; import com.facebook.react.testing.rule.ReactNativeTestRule;
import com.facebook.react.uimanager.PixelUtil; import com.facebook.react.uimanager.PixelUtil;
import java.util.ArrayList;
import java.util.List;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import javax.inject.Provider;
import org.junit.Before; import org.junit.Before;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import com.facebook.react.module.model.ReactModuleInfo;
import com.facebook.react.module.model.ReactModuleInfoProvider;
import com.facebook.react.module.annotations.ReactModule;
@RunWith(AndroidJUnit4.class) @RunWith(AndroidJUnit4.class)
public class ReactRootViewTest { public class ReactRootViewTest {
@ -45,7 +40,8 @@ public class ReactRootViewTest {
} }
final StringRecordingModule mRecordingModule = new StringRecordingModule(); final StringRecordingModule mRecordingModule = new StringRecordingModule();
final ReactPackage mReactPackage = new MainReactPackage() { final ReactPackage mReactPackage =
new MainReactPackage() {
@Override @Override
public NativeModule getModule(String name, ReactApplicationContext context) { public NativeModule getModule(String name, ReactApplicationContext context) {
if (name.equals(StringRecordingModule.NAME)) { if (name.equals(StringRecordingModule.NAME)) {
@ -114,9 +110,8 @@ public class ReactRootViewTest {
new Runnable() { new Runnable() {
@Override @Override
public void run() { public void run() {
rootView.setLayoutParams(new FrameLayout.LayoutParams( rootView.setLayoutParams(
newWidth, new FrameLayout.LayoutParams(newWidth, ViewGroup.LayoutParams.MATCH_PARENT));
ViewGroup.LayoutParams.MATCH_PARENT));
} }
}); });
@ -137,8 +132,7 @@ public class ReactRootViewTest {
public void run() { public void run() {
rootView.setLayoutParams( rootView.setLayoutParams(
new FrameLayout.LayoutParams( new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
ViewGroup.LayoutParams.WRAP_CONTENT));
} }
}); });

Просмотреть файл

@ -5,13 +5,11 @@ import static org.fest.assertions.api.Assertions.assertThat;
import androidx.test.runner.AndroidJUnit4; import androidx.test.runner.AndroidJUnit4;
import com.facebook.react.bridge.NoSuchKeyException; import com.facebook.react.bridge.NoSuchKeyException;
import com.facebook.react.bridge.UnexpectedNativeTypeException; import com.facebook.react.bridge.UnexpectedNativeTypeException;
import com.facebook.react.bridge.WritableArray;
import com.facebook.react.bridge.WritableMap; import com.facebook.react.bridge.WritableMap;
import com.facebook.react.bridge.WritableNativeArray; import com.facebook.react.bridge.WritableNativeArray;
import com.facebook.react.bridge.WritableNativeMap; import com.facebook.react.bridge.WritableNativeMap;
import org.junit.Assert; import org.junit.Assert;
import org.junit.Before; import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;

Просмотреть файл

@ -11,6 +11,8 @@ import com.facebook.debug.debugoverlay.model.DebugOverlayTag;
public interface Printer { public interface Printer {
void logMessage(final DebugOverlayTag tag, final String message, Object... args); void logMessage(final DebugOverlayTag tag, final String message, Object... args);
void logMessage(final DebugOverlayTag tag, final String message); void logMessage(final DebugOverlayTag tag, final String message);
boolean shouldDisplayLogMessage(final DebugOverlayTag tag); boolean shouldDisplayLogMessage(final DebugOverlayTag tag);
} }

Просмотреть файл

@ -28,15 +28,9 @@ public class ReactDebugOverlayTags {
"UI Manager View Operations (requires restart\nwarning: this is spammy)", "UI Manager View Operations (requires restart\nwarning: this is spammy)",
Color.CYAN); Color.CYAN);
public static final DebugOverlayTag FABRIC_UI_MANAGER = public static final DebugOverlayTag FABRIC_UI_MANAGER =
new DebugOverlayTag( new DebugOverlayTag("FabricUIManager", "Fabric UI Manager View Operations", Color.CYAN);
"FabricUIManager",
"Fabric UI Manager View Operations",
Color.CYAN);
public static final DebugOverlayTag FABRIC_RECONCILER = public static final DebugOverlayTag FABRIC_RECONCILER =
new DebugOverlayTag( new DebugOverlayTag("FabricReconciler", "Reconciler for Fabric", Color.CYAN);
"FabricReconciler",
"Reconciler for Fabric",
Color.CYAN);
public static final DebugOverlayTag RELAY = public static final DebugOverlayTag RELAY =
new DebugOverlayTag("Relay", "including prefetching", Color.rgb(0xFF, 0x99, 0x00)); new DebugOverlayTag("Relay", "including prefetching", Color.rgb(0xFF, 0x99, 0x00));
} }

Просмотреть файл

@ -11,11 +11,11 @@ import com.facebook.soloader.SoLoader;
/** /**
* A Java Object that has native memory allocated corresponding to this instance. * A Java Object that has native memory allocated corresponding to this instance.
* *
* NB: THREAD SAFETY (this comment also exists at Countable.cpp) * <p>NB: THREAD SAFETY (this comment also exists at Countable.cpp)
* *
* {@link #dispose} deletes the corresponding native object on whatever thread the method is called * <p>{@link #dispose} deletes the corresponding native object on whatever thread the method is
* on. In the common case when this is called by Countable#finalize(), this will be called on the * called on. In the common case when this is called by Countable#finalize(), this will be called on
* system finalizer thread. If you manually call dispose on the Java object, the native object * the system finalizer thread. If you manually call dispose on the Java object, the native object
* will be deleted synchronously on that thread. * will be deleted synchronously on that thread.
*/ */
@DoNotStrip @DoNotStrip
@ -26,8 +26,7 @@ public class Countable {
} }
// Private C++ instance // Private C++ instance
@DoNotStrip @DoNotStrip private long mInstance = 0;
private long mInstance = 0;
public native void dispose(); public native void dispose();

Просмотреть файл

@ -8,9 +8,7 @@ package com.facebook.jni;
import com.facebook.proguard.annotations.DoNotStrip; import com.facebook.proguard.annotations.DoNotStrip;
import com.facebook.soloader.SoLoader; import com.facebook.soloader.SoLoader;
/** /** Utility class to determine CPU capabilities */
* Utility class to determine CPU capabilities
*/
@DoNotStrip @DoNotStrip
public class CpuCapabilitiesJni { public class CpuCapabilitiesJni {
@ -26,5 +24,4 @@ public class CpuCapabilitiesJni {
@DoNotStrip @DoNotStrip
public static native boolean nativeDeviceSupportsX86(); public static native boolean nativeDeviceSupportsX86();
} }

Просмотреть файл

@ -12,12 +12,12 @@ import java.util.concurrent.atomic.AtomicReference;
/** /**
* A thread which invokes the "destruct" routine for objects after they have been garbage collected. * A thread which invokes the "destruct" routine for objects after they have been garbage collected.
* *
* An object which needs to be destructed should create a static subclass of {@link Destructor}. * <p>An object which needs to be destructed should create a static subclass of {@link Destructor}.
* Once the referent object is garbage collected, the DestructorThread will callback to the * Once the referent object is garbage collected, the DestructorThread will callback to the {@link
* {@link Destructor#destruct()} method. * Destructor#destruct()} method.
* *
* The underlying thread in DestructorThread starts when the first Destructor is constructed * <p>The underlying thread in DestructorThread starts when the first Destructor is constructed and
* and then runs indefinitely. * then runs indefinitely.
*/ */
public class DestructorThread { public class DestructorThread {
@ -48,6 +48,7 @@ public class DestructorThread {
private static DestructorList sDestructorList; private static DestructorList sDestructorList;
/** A thread safe stack where new Destructors are placed before being add to sDestructorList. */ /** A thread safe stack where new Destructors are placed before being add to sDestructorList. */
private static DestructorStack sDestructorStack; private static DestructorStack sDestructorStack;
private static ReferenceQueue sReferenceQueue; private static ReferenceQueue sReferenceQueue;
private static Thread sThread; private static Thread sThread;
@ -55,7 +56,8 @@ public class DestructorThread {
sDestructorStack = new DestructorStack(); sDestructorStack = new DestructorStack();
sReferenceQueue = new ReferenceQueue(); sReferenceQueue = new ReferenceQueue();
sDestructorList = new DestructorList(); sDestructorList = new DestructorList();
sThread = new Thread("HybridData DestructorThread") { sThread =
new Thread("HybridData DestructorThread") {
@Override @Override
public void run() { public void run() {
while (true) { while (true) {

Просмотреть файл

@ -4,8 +4,8 @@
// LICENSE file in the root directory of this source tree. // LICENSE file in the root directory of this source tree.
package com.facebook.jni; package com.facebook.jni;
import com.facebook.proguard.annotations.DoNotStrip; import com.facebook.proguard.annotations.DoNotStrip;
@DoNotStrip @DoNotStrip
public abstract class HybridClassBase extends HybridData { public abstract class HybridClassBase extends HybridData {}
}

Просмотреть файл

@ -5,19 +5,16 @@
package com.facebook.jni; package com.facebook.jni;
import android.util.Log;
import com.facebook.proguard.annotations.DoNotStrip; import com.facebook.proguard.annotations.DoNotStrip;
import com.facebook.soloader.SoLoader; import com.facebook.soloader.SoLoader;
/** /**
* This object holds a native C++ member for hybrid Java/C++ objects. * This object holds a native C++ member for hybrid Java/C++ objects.
* *
* NB: THREAD SAFETY * <p>NB: THREAD SAFETY
* *
* {@link #resetNative} deletes the corresponding native object synchronously on whatever thread * <p>{@link #resetNative} deletes the corresponding native object synchronously on whatever thread
* the method is called on. Otherwise, deletion will occur on the {@link DestructorThread} * the method is called on. Otherwise, deletion will occur on the {@link DestructorThread} thread.
* thread.
*/ */
@DoNotStrip @DoNotStrip
public class HybridData { public class HybridData {
@ -26,26 +23,24 @@ public class HybridData {
SoLoader.loadLibrary("fb"); SoLoader.loadLibrary("fb");
} }
@DoNotStrip @DoNotStrip private Destructor mDestructor = new Destructor(this);
private Destructor mDestructor = new Destructor(this);
/** /**
* To explicitly delete the instance, call resetNative(). If the C++ * To explicitly delete the instance, call resetNative(). If the C++ instance is referenced after
* instance is referenced after this is called, a NullPointerException will * this is called, a NullPointerException will be thrown. resetNative() may be called multiple
* be thrown. resetNative() may be called multiple times safely. Because * times safely. Because the {@link DestructorThread} also calls resetNative, the instance will
* the {@link DestructorThread} also calls resetNative, the instance will not leak if this is * not leak if this is not called, but timing of deletion and the thread the C++ dtor is called on
* not called, but timing of deletion and the thread the C++ dtor is called * will be at the whim of the Java GC. If you want to control the thread and timing of the
* on will be at the whim of the Java GC. If you want to control the thread * destructor, you should call resetNative() explicitly.
* and timing of the destructor, you should call resetNative() explicitly.
*/ */
public synchronized void resetNative() { public synchronized void resetNative() {
mDestructor.destruct(); mDestructor.destruct();
} }
/** /**
* N.B. Thread safety. * N.B. Thread safety. If you call isValid from a different thread than {@link #resetNative()}
* If you call isValid from a different thread than {@link #resetNative()} then be sure to * then be sure to do so while synchronizing on the hybrid. For example:
* do so while synchronizing on the hybrid. For example: *
* <pre><code> * <pre><code>
* synchronized(hybrid) { * synchronized(hybrid) {
* if (hybrid.isValid) { * if (hybrid.isValid) {
@ -61,8 +56,7 @@ public class HybridData {
public static class Destructor extends DestructorThread.Destructor { public static class Destructor extends DestructorThread.Destructor {
// Private C++ instance // Private C++ instance
@DoNotStrip @DoNotStrip private long mNativePointer;
private long mNativePointer;
Destructor(Object referent) { Destructor(Object referent) {
super(referent); super(referent);

Просмотреть файл

@ -1,31 +1,26 @@
/** /**
* Copyright (c) Facebook, Inc. and its affiliates. * Copyright (c) Facebook, Inc. and its affiliates.
* *
* This source code is licensed under the MIT license found in the * <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* LICENSE file in the root directory of this source tree. * directory of this source tree.
*/ */
package com.facebook.jni; package com.facebook.jni;
import com.facebook.proguard.annotations.DoNotStrip; import com.facebook.proguard.annotations.DoNotStrip;
import java.util.Iterator;
import javax.annotation.Nullable; import javax.annotation.Nullable;
import java.util.Iterator;
/** /**
* To iterate over an Iterator from C++ requires two calls per entry: hasNext() * To iterate over an Iterator from C++ requires two calls per entry: hasNext() and next(). This
* and next(). This helper reduces it to one call and one field get per entry. * helper reduces it to one call and one field get per entry. It does not use a generic argument,
* It does not use a generic argument, since in C++, the types will be erased, * since in C++, the types will be erased, anyway. This is *not* a {@link java.util.Iterator}.
* anyway. This is *not* a {@link java.util.Iterator}.
*/ */
@DoNotStrip @DoNotStrip
public class IteratorHelper { public class IteratorHelper {
private final Iterator mIterator; private final Iterator mIterator;
// This is private, but accessed via JNI. // This is private, but accessed via JNI.
@DoNotStrip @DoNotStrip private @Nullable Object mElement;
private @Nullable Object mElement;
@DoNotStrip @DoNotStrip
public IteratorHelper(Iterator iterator) { public IteratorHelper(Iterator iterator) {
@ -38,8 +33,8 @@ public class IteratorHelper {
} }
/** /**
* Moves the helper to the next entry in the map, if any. Returns true iff * Moves the helper to the next entry in the map, if any. Returns true iff there is an entry to
* there is an entry to read. * read.
*/ */
@DoNotStrip @DoNotStrip
boolean hasNext() { boolean hasNext() {

Просмотреть файл

@ -1,24 +1,21 @@
/** /**
* Copyright (c) Facebook, Inc. and its affiliates. * Copyright (c) Facebook, Inc. and its affiliates.
* *
* This source code is licensed under the MIT license found in the * <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* LICENSE file in the root directory of this source tree. * directory of this source tree.
*/ */
package com.facebook.jni; package com.facebook.jni;
import javax.annotation.Nullable; import com.facebook.proguard.annotations.DoNotStrip;
import java.util.Iterator; import java.util.Iterator;
import java.util.Map; import java.util.Map;
import javax.annotation.Nullable;
import com.facebook.proguard.annotations.DoNotStrip;
/** /**
* To iterate over a Map from C++ requires four calls per entry: hasNext(), * To iterate over a Map from C++ requires four calls per entry: hasNext(), next(), getKey(),
* next(), getKey(), getValue(). This helper reduces it to one call and two * getValue(). This helper reduces it to one call and two field gets per entry. It does not use a
* field gets per entry. It does not use a generic argument, since in C++, the * generic argument, since in C++, the types will be erased, anyway. This is *not* a {@link
* types will be erased, anyway. This is *not* a {@link java.util.Iterator}. * java.util.Iterator}.
*/ */
@DoNotStrip @DoNotStrip
public class MapIteratorHelper { public class MapIteratorHelper {
@ -32,8 +29,8 @@ public class MapIteratorHelper {
} }
/** /**
* Moves the helper to the next entry in the map, if any. Returns true iff * Moves the helper to the next entry in the map, if any. Returns true iff there is an entry to
* there is an entry to read. * read.
*/ */
@DoNotStrip @DoNotStrip
boolean hasNext() { boolean hasNext() {

Просмотреть файл

@ -1,18 +1,14 @@
/** /**
* Copyright (c) Facebook, Inc. and its affiliates. * Copyright (c) Facebook, Inc. and its affiliates.
* *
* This source code is licensed under the MIT license found in the * <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* LICENSE file in the root directory of this source tree. * directory of this source tree.
*/ */
package com.facebook.jni; package com.facebook.jni;
import com.facebook.jni.HybridData;
import com.facebook.proguard.annotations.DoNotStrip; import com.facebook.proguard.annotations.DoNotStrip;
/** /** A Runnable that has a native run implementation. */
* A Runnable that has a native run implementation.
*/
@DoNotStrip @DoNotStrip
public class NativeRunnable implements Runnable { public class NativeRunnable implements Runnable {

Просмотреть файл

@ -1,19 +1,15 @@
/** /**
* Copyright (c) Facebook, Inc. and its affiliates. * Copyright (c) Facebook, Inc. and its affiliates.
* *
* This source code is licensed under the MIT license found in the * <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* LICENSE file in the root directory of this source tree. * directory of this source tree.
*/ */
package com.facebook.perftest; package com.facebook.perftest;
/** /** PerfTestConfig stub. */
* PerfTestConfig stub.
*/
public class PerfTestConfig { public class PerfTestConfig {
public boolean isRunningInPerfTest() { public boolean isRunningInPerfTest() {
return false; return false;
} }
} }

Просмотреть файл

@ -1,24 +1,22 @@
/** /**
* Copyright (c) Facebook, Inc. and its affiliates. * Copyright (c) Facebook, Inc. and its affiliates.
* *
* This source code is licensed under the MIT license found in the * <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* LICENSE file in the root directory of this source tree. * directory of this source tree.
*/ */
package com.facebook.proguard.annotations; package com.facebook.proguard.annotations;
import static java.lang.annotation.RetentionPolicy.CLASS;
import java.lang.annotation.ElementType; import java.lang.annotation.ElementType;
import java.lang.annotation.Retention; import java.lang.annotation.Retention;
import java.lang.annotation.Target; import java.lang.annotation.Target;
import static java.lang.annotation.RetentionPolicy.CLASS;
/** /**
* Add this annotation to a class, method, or field to instruct Proguard to not strip it out. * Add this annotation to a class, method, or field to instruct Proguard to not strip it out.
* *
* This is useful for methods called via reflection that could appear as unused to Proguard. * <p>This is useful for methods called via reflection that could appear as unused to Proguard.
*/ */
@Target({ElementType.TYPE, ElementType.FIELD, ElementType.METHOD, ElementType.CONSTRUCTOR}) @Target({ElementType.TYPE, ElementType.FIELD, ElementType.METHOD, ElementType.CONSTRUCTOR})
@Retention(CLASS) @Retention(CLASS)
public @interface DoNotStrip { public @interface DoNotStrip {}
}

Просмотреть файл

@ -1,28 +1,26 @@
/** /**
* Copyright (c) Facebook, Inc. and its affiliates. * Copyright (c) Facebook, Inc. and its affiliates.
* *
* This source code is licensed under the MIT license found in the * <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* LICENSE file in the root directory of this source tree. * directory of this source tree.
*/ */
package com.facebook.proguard.annotations; package com.facebook.proguard.annotations;
import static java.lang.annotation.RetentionPolicy.CLASS;
import java.lang.annotation.ElementType; import java.lang.annotation.ElementType;
import java.lang.annotation.Retention; import java.lang.annotation.Retention;
import java.lang.annotation.Target; import java.lang.annotation.Target;
import static java.lang.annotation.RetentionPolicy.CLASS;
/** /**
* Add this annotation to a class, to keep all "void set*(***)" and get* methods. * Add this annotation to a class, to keep all "void set*(***)" and get* methods.
* *
* <p>This is useful for classes that are controlled by animator-like classes that control * <p>This is useful for classes that are controlled by animator-like classes that control various
* various properties with reflection. * properties with reflection.
* *
* <p><b>NOTE:</b> This is <em>not</em> needed for Views because their getters and setters * <p><b>NOTE:</b> This is <em>not</em> needed for Views because their getters and setters are
* are automatically kept by the default Android SDK ProGuard config. * automatically kept by the default Android SDK ProGuard config.
*/ */
@Target({ElementType.TYPE}) @Target({ElementType.TYPE})
@Retention(CLASS) @Retention(CLASS)
public @interface KeepGettersAndSetters { public @interface KeepGettersAndSetters {}
}

Просмотреть файл

@ -20,7 +20,6 @@ import java.util.ListIterator;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import javax.annotation.Nullable; import javax.annotation.Nullable;
import com.facebook.react.TurboReactPackage;
/** /**
* {@code CompositeReactPackage} allows to create a single package composed of views and modules * {@code CompositeReactPackage} allows to create a single package composed of views and modules
@ -50,11 +49,11 @@ public class CompositeReactPackage implements ViewManagerOnDemandReactPackage, R
final Map<String, NativeModule> moduleMap = new HashMap<>(); final Map<String, NativeModule> moduleMap = new HashMap<>();
for (ReactPackage reactPackage : mChildReactPackages) { for (ReactPackage reactPackage : mChildReactPackages) {
/** /**
* For now, we eagerly initialize the NativeModules inside TurboReactPackages. * For now, we eagerly initialize the NativeModules inside TurboReactPackages. Ultimately, we
* Ultimately, we should turn CompositeReactPackage into a TurboReactPackage * should turn CompositeReactPackage into a TurboReactPackage and remove this eager
* and remove this eager initialization. * initialization.
* *
* TODO: T45627020 * <p>TODO: T45627020
*/ */
if (reactPackage instanceof TurboReactPackage) { if (reactPackage instanceof TurboReactPackage) {
TurboReactPackage turboReactPackage = (TurboReactPackage) reactPackage; TurboReactPackage turboReactPackage = (TurboReactPackage) reactPackage;

Просмотреть файл

@ -6,6 +6,7 @@
*/ */
package com.facebook.react; package com.facebook.react;
import static com.facebook.react.bridge.ReactMarkerConstants.*;
import static com.facebook.react.bridge.ReactMarkerConstants.CREATE_UI_MANAGER_MODULE_END; import static com.facebook.react.bridge.ReactMarkerConstants.CREATE_UI_MANAGER_MODULE_END;
import static com.facebook.react.bridge.ReactMarkerConstants.CREATE_UI_MANAGER_MODULE_START; import static com.facebook.react.bridge.ReactMarkerConstants.CREATE_UI_MANAGER_MODULE_START;
import static com.facebook.react.bridge.ReactMarkerConstants.PROCESS_CORE_REACT_PACKAGE_END; import static com.facebook.react.bridge.ReactMarkerConstants.PROCESS_CORE_REACT_PACKAGE_END;
@ -18,11 +19,11 @@ import com.facebook.react.module.annotations.ReactModule;
import com.facebook.react.module.annotations.ReactModuleList; import com.facebook.react.module.annotations.ReactModuleList;
import com.facebook.react.module.model.ReactModuleInfo; import com.facebook.react.module.model.ReactModuleInfo;
import com.facebook.react.module.model.ReactModuleInfoProvider; import com.facebook.react.module.model.ReactModuleInfoProvider;
import com.facebook.react.modules.core.DefaultHardwareBackBtnHandler;
import com.facebook.react.modules.core.DeviceEventManagerModule; import com.facebook.react.modules.core.DeviceEventManagerModule;
import com.facebook.react.modules.core.ExceptionsManagerModule; import com.facebook.react.modules.core.ExceptionsManagerModule;
import com.facebook.react.modules.core.Timing;
import com.facebook.react.modules.core.DefaultHardwareBackBtnHandler;
import com.facebook.react.modules.core.HeadlessJsTaskSupportModule; import com.facebook.react.modules.core.HeadlessJsTaskSupportModule;
import com.facebook.react.modules.core.Timing;
import com.facebook.react.modules.debug.DevSettingsModule; import com.facebook.react.modules.debug.DevSettingsModule;
import com.facebook.react.modules.debug.SourceCodeModule; import com.facebook.react.modules.debug.SourceCodeModule;
import com.facebook.react.modules.deviceinfo.DeviceInfoModule; import com.facebook.react.modules.deviceinfo.DeviceInfoModule;
@ -31,14 +32,10 @@ import com.facebook.react.uimanager.UIImplementationProvider;
import com.facebook.react.uimanager.UIManagerModule; import com.facebook.react.uimanager.UIManagerModule;
import com.facebook.react.uimanager.ViewManager; import com.facebook.react.uimanager.ViewManager;
import com.facebook.systrace.Systrace; import com.facebook.systrace.Systrace;
import java.util.Collections;
import javax.annotation.Nullable;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import javax.annotation.Nullable;
import static com.facebook.react.bridge.ReactMarkerConstants.*;
/** /**
* This is the basic module to support React Native. The debug modules are now in DebugCorePackage. * This is the basic module to support React Native. The debug modules are now in DebugCorePackage.

Просмотреть файл

@ -1,10 +1,9 @@
/** /**
* Copyright (c) Facebook, Inc. and its affiliates. * Copyright (c) Facebook, Inc. and its affiliates.
* *
* This source code is licensed under the MIT license found in the * <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* LICENSE file in the root directory of this source tree. * directory of this source tree.
*/ */
package com.facebook.react; package com.facebook.react;
import com.facebook.react.bridge.ModuleSpec; import com.facebook.react.bridge.ModuleSpec;
@ -27,12 +26,10 @@ import javax.inject.Provider;
nativeModules = { nativeModules = {
JSCHeapCapture.class, JSCHeapCapture.class,
JSDevSupport.class, JSDevSupport.class,
} })
)
/* package */ class DebugCorePackage extends LazyReactPackage { /* package */ class DebugCorePackage extends LazyReactPackage {
DebugCorePackage() { DebugCorePackage() {}
}
@Override @Override
public List<ModuleSpec> getNativeModules(final ReactApplicationContext reactContext) { public List<ModuleSpec> getNativeModules(final ReactApplicationContext reactContext) {

Просмотреть файл

@ -5,13 +5,10 @@
package com.facebook.react; package com.facebook.react;
import com.facebook.react.bridge.NativeModule;
import javax.inject.Provider; import javax.inject.Provider;
import com.facebook.react.bridge.NativeModule; /** Provider for an already initialized and non-lazy NativeModule. */
/**
* Provider for an already initialized and non-lazy NativeModule.
*/
public class EagerModuleProvider implements Provider<NativeModule> { public class EagerModuleProvider implements Provider<NativeModule> {
private final NativeModule mModule; private final NativeModule mModule;

Просмотреть файл

@ -1,17 +1,11 @@
/** /**
* Copyright (c) Facebook, Inc. and its affiliates. * Copyright (c) Facebook, Inc. and its affiliates.
* *
* This source code is licensed under the MIT license found in the * <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* LICENSE file in the root directory of this source tree. * directory of this source tree.
*/ */
package com.facebook.react; package com.facebook.react;
import javax.annotation.Nullable;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
import android.annotation.SuppressLint; import android.annotation.SuppressLint;
import android.app.Service; import android.app.Service;
import android.content.BroadcastReceiver; import android.content.BroadcastReceiver;
@ -19,23 +13,25 @@ import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.os.IBinder; import android.os.IBinder;
import android.os.PowerManager; import android.os.PowerManager;
import com.facebook.infer.annotation.Assertions; import com.facebook.infer.annotation.Assertions;
import com.facebook.react.bridge.ReactContext; import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.UiThreadUtil; import com.facebook.react.bridge.UiThreadUtil;
import com.facebook.react.jstasks.HeadlessJsTaskEventListener;
import com.facebook.react.jstasks.HeadlessJsTaskConfig; import com.facebook.react.jstasks.HeadlessJsTaskConfig;
import com.facebook.react.jstasks.HeadlessJsTaskContext; import com.facebook.react.jstasks.HeadlessJsTaskContext;
import com.facebook.react.jstasks.HeadlessJsTaskEventListener;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
import javax.annotation.Nullable;
/** /**
* Base class for running JS without a UI. Generally, you only need to override * Base class for running JS without a UI. Generally, you only need to override {@link
* {@link #getTaskConfig}, which is called for every {@link #onStartCommand}. The * #getTaskConfig}, which is called for every {@link #onStartCommand}. The result, if not {@code
* result, if not {@code null}, is used to run a JS task. * null}, is used to run a JS task.
* *
* If you need more fine-grained control over how tasks are run, you can override * <p>If you need more fine-grained control over how tasks are run, you can override {@link
* {@link #onStartCommand} and call {@link #startTask} depending on your custom logic. * #onStartCommand} and call {@link #startTask} depending on your custom logic.
* *
* If you're starting a {@code HeadlessJsTaskService} from a {@code BroadcastReceiver} (e.g. * <p>If you're starting a {@code HeadlessJsTaskService} from a {@code BroadcastReceiver} (e.g.
* handling push notifications), make sure to call {@link #acquireWakeLockNow} before returning from * handling push notifications), make sure to call {@link #acquireWakeLockNow} before returning from
* {@link BroadcastReceiver#onReceive}, to make sure the device doesn't go to sleep before the * {@link BroadcastReceiver#onReceive}, to make sure the device doesn't go to sleep before the
* service is started. * service is started.
@ -57,9 +53,10 @@ public abstract class HeadlessJsTaskService extends Service implements HeadlessJ
/** /**
* Called from {@link #onStartCommand} to create a {@link HeadlessJsTaskConfig} for this intent. * Called from {@link #onStartCommand} to create a {@link HeadlessJsTaskConfig} for this intent.
*
* @param intent the {@link Intent} received in {@link #onStartCommand}. * @param intent the {@link Intent} received in {@link #onStartCommand}.
* @return a {@link HeadlessJsTaskConfig} to be used with {@link #startTask}, or * @return a {@link HeadlessJsTaskConfig} to be used with {@link #startTask}, or {@code null} to
* {@code null} to ignore this command. * ignore this command.
*/ */
protected @Nullable HeadlessJsTaskConfig getTaskConfig(Intent intent) { protected @Nullable HeadlessJsTaskConfig getTaskConfig(Intent intent) {
return null; return null;
@ -73,9 +70,9 @@ public abstract class HeadlessJsTaskService extends Service implements HeadlessJ
if (sWakeLock == null || !sWakeLock.isHeld()) { if (sWakeLock == null || !sWakeLock.isHeld()) {
PowerManager powerManager = PowerManager powerManager =
Assertions.assertNotNull((PowerManager) context.getSystemService(POWER_SERVICE)); Assertions.assertNotNull((PowerManager) context.getSystemService(POWER_SERVICE));
sWakeLock = powerManager.newWakeLock( sWakeLock =
PowerManager.PARTIAL_WAKE_LOCK, powerManager.newWakeLock(
HeadlessJsTaskService.class.getCanonicalName()); PowerManager.PARTIAL_WAKE_LOCK, HeadlessJsTaskService.class.getCanonicalName());
sWakeLock.setReferenceCounted(false); sWakeLock.setReferenceCounted(false);
sWakeLock.acquire(); sWakeLock.acquire();
} }
@ -89,7 +86,7 @@ public abstract class HeadlessJsTaskService extends Service implements HeadlessJ
/** /**
* Start a task. This method handles starting a new React instance if required. * Start a task. This method handles starting a new React instance if required.
* *
* Has to be called on the UI thread. * <p>Has to be called on the UI thread.
* *
* @param taskConfig describes what task to start and the parameters to pass to it * @param taskConfig describes what task to start and the parameters to pass to it
*/ */
@ -100,8 +97,8 @@ public abstract class HeadlessJsTaskService extends Service implements HeadlessJ
getReactNativeHost().getReactInstanceManager(); getReactNativeHost().getReactInstanceManager();
ReactContext reactContext = reactInstanceManager.getCurrentReactContext(); ReactContext reactContext = reactInstanceManager.getCurrentReactContext();
if (reactContext == null) { if (reactContext == null) {
reactInstanceManager reactInstanceManager.addReactInstanceEventListener(
.addReactInstanceEventListener(new ReactInstanceManager.ReactInstanceEventListener() { new ReactInstanceManager.ReactInstanceEventListener() {
@Override @Override
public void onReactContextInitialized(ReactContext reactContext) { public void onReactContextInitialized(ReactContext reactContext) {
invokeStartTask(reactContext, taskConfig); invokeStartTask(reactContext, taskConfig);
@ -115,7 +112,8 @@ public abstract class HeadlessJsTaskService extends Service implements HeadlessJ
} }
private void invokeStartTask(ReactContext reactContext, final HeadlessJsTaskConfig taskConfig) { private void invokeStartTask(ReactContext reactContext, final HeadlessJsTaskConfig taskConfig) {
final HeadlessJsTaskContext headlessJsTaskContext = HeadlessJsTaskContext.getInstance(reactContext); final HeadlessJsTaskContext headlessJsTaskContext =
HeadlessJsTaskContext.getInstance(reactContext);
headlessJsTaskContext.addTaskEventListener(this); headlessJsTaskContext.addTaskEventListener(this);
UiThreadUtil.runOnUiThread( UiThreadUtil.runOnUiThread(
@ -125,8 +123,7 @@ public abstract class HeadlessJsTaskService extends Service implements HeadlessJ
int taskId = headlessJsTaskContext.startTask(taskConfig); int taskId = headlessJsTaskContext.startTask(taskConfig);
mActiveTasks.add(taskId); mActiveTasks.add(taskId);
} }
} });
);
} }
@Override @Override
@ -160,10 +157,10 @@ public abstract class HeadlessJsTaskService extends Service implements HeadlessJ
/** /**
* Get the {@link ReactNativeHost} used by this app. By default, assumes {@link #getApplication()} * Get the {@link ReactNativeHost} used by this app. By default, assumes {@link #getApplication()}
* is an instance of {@link ReactApplication} and calls * is an instance of {@link ReactApplication} and calls {@link
* {@link ReactApplication#getReactNativeHost()}. Override this method if your application class * ReactApplication#getReactNativeHost()}. Override this method if your application class does not
* does not implement {@code ReactApplication} or you simply have a different mechanism for * implement {@code ReactApplication} or you simply have a different mechanism for storing a
* storing a {@code ReactNativeHost}, e.g. as a static field somewhere. * {@code ReactNativeHost}, e.g. as a static field somewhere.
*/ */
protected ReactNativeHost getReactNativeHost() { protected ReactNativeHost getReactNativeHost() {
return ((ReactApplication) getApplication()).getReactNativeHost(); return ((ReactApplication) getApplication()).getReactNativeHost();

Просмотреть файл

@ -76,7 +76,8 @@ public abstract class LazyReactPackage implements ReactPackage {
* @param reactContext * @param reactContext
* @return * @return
*/ */
public Iterable<ModuleHolder> getNativeModuleIterator(final ReactApplicationContext reactContext) { public Iterable<ModuleHolder> getNativeModuleIterator(
final ReactApplicationContext reactContext) {
final Map<String, ReactModuleInfo> reactModuleInfoMap = final Map<String, ReactModuleInfo> reactModuleInfoMap =
getReactModuleInfoProvider().getReactModuleInfos(); getReactModuleInfoProvider().getReactModuleInfos();
final List<ModuleSpec> nativeModules = getNativeModules(reactContext); final List<ModuleSpec> nativeModules = getNativeModules(reactContext);

Просмотреть файл

@ -13,9 +13,7 @@ import java.util.Collections;
import java.util.LinkedHashSet; import java.util.LinkedHashSet;
import java.util.Set; import java.util.Set;
/** /** Translates and routes memory pressure events to the current catalyst instance. */
* Translates and routes memory pressure events to the current catalyst instance.
*/
public class MemoryPressureRouter implements ComponentCallbacks2 { public class MemoryPressureRouter implements ComponentCallbacks2 {
private final Set<MemoryPressureListener> mListeners = private final Set<MemoryPressureListener> mListeners =
Collections.synchronizedSet(new LinkedHashSet<MemoryPressureListener>()); Collections.synchronizedSet(new LinkedHashSet<MemoryPressureListener>());
@ -28,16 +26,12 @@ public class MemoryPressureRouter implements ComponentCallbacks2 {
context.getApplicationContext().unregisterComponentCallbacks(this); context.getApplicationContext().unregisterComponentCallbacks(this);
} }
/** /** Add a listener to be notified of memory pressure events. */
* Add a listener to be notified of memory pressure events.
*/
public void addMemoryPressureListener(MemoryPressureListener listener) { public void addMemoryPressureListener(MemoryPressureListener listener) {
mListeners.add(listener); mListeners.add(listener);
} }
/** /** Remove a listener previously added with {@link #addMemoryPressureListener}. */
* Remove a listener previously added with {@link #addMemoryPressureListener}.
*/
public void removeMemoryPressureListener(MemoryPressureListener listener) { public void removeMemoryPressureListener(MemoryPressureListener listener) {
mListeners.remove(listener); mListeners.remove(listener);
} }
@ -48,12 +42,10 @@ public class MemoryPressureRouter implements ComponentCallbacks2 {
} }
@Override @Override
public void onConfigurationChanged(Configuration newConfig) { public void onConfigurationChanged(Configuration newConfig) {}
}
@Override @Override
public void onLowMemory() { public void onLowMemory() {}
}
private void dispatchMemoryPressure(int level) { private void dispatchMemoryPressure(int level) {
// copy listeners array to avoid ConcurrentModificationException if any of the listeners remove // copy listeners array to avoid ConcurrentModificationException if any of the listeners remove

Просмотреть файл

@ -64,7 +64,8 @@ public class NativeModuleRegistryBuilder {
// already in the list, and then NOT add the new module, since that will be directly exposed // already in the list, and then NOT add the new module, since that will be directly exposed
// Note that is someone uses {@link NativeModuleRegistry#registerModules}, we will NOT check // Note that is someone uses {@link NativeModuleRegistry#registerModules}, we will NOT check
// for TurboModules - assuming that people wanted to explicitly register native modules there // for TurboModules - assuming that people wanted to explicitly register native modules
// there
continue; continue;
} }
mModules.put(name, moduleHolder); mModules.put(name, moduleHolder);

Просмотреть файл

@ -1,26 +1,21 @@
/** /**
* Copyright (c) Facebook, Inc. and its affiliates. * Copyright (c) Facebook, Inc. and its affiliates.
* *
* This source code is licensed under the MIT license found in the * <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* LICENSE file in the root directory of this source tree. * directory of this source tree.
*/ */
package com.facebook.react; package com.facebook.react;
import javax.annotation.Nullable;
import android.content.Intent; import android.content.Intent;
import android.os.Bundle; import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.view.KeyEvent; import android.view.KeyEvent;
import androidx.appcompat.app.AppCompatActivity;
import com.facebook.react.modules.core.DefaultHardwareBackBtnHandler; import com.facebook.react.modules.core.DefaultHardwareBackBtnHandler;
import com.facebook.react.modules.core.PermissionAwareActivity; import com.facebook.react.modules.core.PermissionAwareActivity;
import com.facebook.react.modules.core.PermissionListener; import com.facebook.react.modules.core.PermissionListener;
import javax.annotation.Nullable;
/** /** Base Activity for React Native applications. */
* Base Activity for React Native applications.
*/
public abstract class ReactActivity extends AppCompatActivity public abstract class ReactActivity extends AppCompatActivity
implements DefaultHardwareBackBtnHandler, PermissionAwareActivity { implements DefaultHardwareBackBtnHandler, PermissionAwareActivity {
@ -31,17 +26,14 @@ public abstract class ReactActivity extends AppCompatActivity
} }
/** /**
* Returns the name of the main component registered from JavaScript. * Returns the name of the main component registered from JavaScript. This is used to schedule
* This is used to schedule rendering of the component. * rendering of the component. e.g. "MoviesApp"
* e.g. "MoviesApp"
*/ */
protected @Nullable String getMainComponentName() { protected @Nullable String getMainComponentName() {
return null; return null;
} }
/** /** Called at construction time, override if you have a custom delegate implementation. */
* Called at construction time, override if you have a custom delegate implementation.
*/
protected ReactActivityDelegate createReactActivityDelegate() { protected ReactActivityDelegate createReactActivityDelegate() {
return new ReactActivityDelegate(this, getMainComponentName()); return new ReactActivityDelegate(this, getMainComponentName());
} }
@ -111,17 +103,13 @@ public abstract class ReactActivity extends AppCompatActivity
@Override @Override
public void requestPermissions( public void requestPermissions(
String[] permissions, String[] permissions, int requestCode, PermissionListener listener) {
int requestCode,
PermissionListener listener) {
mDelegate.requestPermissions(permissions, requestCode, listener); mDelegate.requestPermissions(permissions, requestCode, listener);
} }
@Override @Override
public void onRequestPermissionsResult( public void onRequestPermissionsResult(
int requestCode, int requestCode, String[] permissions, int[] grantResults) {
String[] permissions,
int[] grantResults) {
mDelegate.onRequestPermissionsResult(requestCode, permissions, grantResults); mDelegate.onRequestPermissionsResult(requestCode, permissions, grantResults);
} }

Просмотреть файл

@ -12,12 +12,9 @@ import android.content.Intent;
import android.os.Build; import android.os.Build;
import android.os.Bundle; import android.os.Bundle;
import android.view.KeyEvent; import android.view.KeyEvent;
import com.facebook.infer.annotation.Assertions; import com.facebook.infer.annotation.Assertions;
import com.facebook.react.bridge.Callback; import com.facebook.react.bridge.Callback;
import com.facebook.react.uimanager.RootView;
import com.facebook.react.modules.core.PermissionListener; import com.facebook.react.modules.core.PermissionListener;
import javax.annotation.Nullable; import javax.annotation.Nullable;
/** /**
@ -54,11 +51,11 @@ public class ReactActivityDelegate {
} }
/** /**
* Get the {@link ReactNativeHost} used by this app. By default, assumes * Get the {@link ReactNativeHost} used by this app. By default, assumes {@link
* {@link Activity#getApplication()} is an instance of {@link ReactApplication} and calls * Activity#getApplication()} is an instance of {@link ReactApplication} and calls {@link
* {@link ReactApplication#getReactNativeHost()}. Override this method if your application class * ReactApplication#getReactNativeHost()}. Override this method if your application class does not
* does not implement {@code ReactApplication} or you simply have a different mechanism for * implement {@code ReactApplication} or you simply have a different mechanism for storing a
* storing a {@code ReactNativeHost}, e.g. as a static field somewhere. * {@code ReactNativeHost}, e.g. as a static field somewhere.
*/ */
protected ReactNativeHost getReactNativeHost() { protected ReactNativeHost getReactNativeHost() {
return ((ReactApplication) getPlainActivity().getApplication()).getReactNativeHost(); return ((ReactApplication) getPlainActivity().getApplication()).getReactNativeHost();
@ -74,7 +71,9 @@ public class ReactActivityDelegate {
protected void onCreate(Bundle savedInstanceState) { protected void onCreate(Bundle savedInstanceState) {
String mainComponentName = getMainComponentName(); String mainComponentName = getMainComponentName();
mReactDelegate = new ReactDelegate(getPlainActivity(), getReactNativeHost(), mainComponentName, getLaunchOptions()); mReactDelegate =
new ReactDelegate(
getPlainActivity(), getReactNativeHost(), mainComponentName, getLaunchOptions());
if (mMainComponentName != null) { if (mMainComponentName != null) {
loadApp(mainComponentName); loadApp(mainComponentName);
} }
@ -150,21 +149,20 @@ public class ReactActivityDelegate {
@TargetApi(Build.VERSION_CODES.M) @TargetApi(Build.VERSION_CODES.M)
public void requestPermissions( public void requestPermissions(
String[] permissions, String[] permissions, int requestCode, PermissionListener listener) {
int requestCode,
PermissionListener listener) {
mPermissionListener = listener; mPermissionListener = listener;
getPlainActivity().requestPermissions(permissions, requestCode); getPlainActivity().requestPermissions(permissions, requestCode);
} }
public void onRequestPermissionsResult( public void onRequestPermissionsResult(
final int requestCode, final int requestCode, final String[] permissions, final int[] grantResults) {
final String[] permissions, mPermissionsCallback =
final int[] grantResults) { new Callback() {
mPermissionsCallback = new Callback() {
@Override @Override
public void invoke(Object... args) { public void invoke(Object... args) {
if (mPermissionListener != null && mPermissionListener.onRequestPermissionsResult(requestCode, permissions, grantResults)) { if (mPermissionListener != null
&& mPermissionListener.onRequestPermissionsResult(
requestCode, permissions, grantResults)) {
mPermissionListener = null; mPermissionListener = null;
} }
} }

Просмотреть файл

@ -1,31 +1,27 @@
/** /**
* Copyright (c) Facebook, Inc. and its affiliates. * Copyright (c) Facebook, Inc. and its affiliates.
* *
* This source code is licensed under the MIT license found in the * <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* LICENSE file in the root directory of this source tree. * directory of this source tree.
*/ */
package com.facebook.react; package com.facebook.react;
import android.view.KeyEvent; import android.view.KeyEvent;
import android.view.View; import android.view.View;
import com.facebook.react.bridge.WritableMap; import com.facebook.react.bridge.WritableMap;
import com.facebook.react.bridge.WritableNativeMap; import com.facebook.react.bridge.WritableNativeMap;
import com.facebook.react.common.MapBuilder; import com.facebook.react.common.MapBuilder;
import java.util.Map; import java.util.Map;
/** /** Responsible for dispatching events specific for hardware inputs. */
* Responsible for dispatching events specific for hardware inputs.
*/
public class ReactAndroidHWInputDeviceHelper { public class ReactAndroidHWInputDeviceHelper {
/** /**
* Contains a mapping between handled KeyEvents and the corresponding navigation event * Contains a mapping between handled KeyEvents and the corresponding navigation event that should
* that should be fired when the KeyEvent is received. * be fired when the KeyEvent is received.
*/ */
private static final Map<Integer, String> KEY_EVENTS_ACTIONS = MapBuilder.<Integer, String>builder() private static final Map<Integer, String> KEY_EVENTS_ACTIONS =
MapBuilder.<Integer, String>builder()
.put(KeyEvent.KEYCODE_DPAD_CENTER, "select") .put(KeyEvent.KEYCODE_DPAD_CENTER, "select")
.put(KeyEvent.KEYCODE_ENTER, "select") .put(KeyEvent.KEYCODE_ENTER, "select")
.put(KeyEvent.KEYCODE_SPACE, "select") .put(KeyEvent.KEYCODE_SPACE, "select")
@ -39,9 +35,8 @@ public class ReactAndroidHWInputDeviceHelper {
.build(); .build();
/** /**
* We keep a reference to the last focused view id * We keep a reference to the last focused view id so that we can send it as a target for key
* so that we can send it as a target for key events * events and be able to send a blur event when focus changes.
* and be able to send a blur event when focus changes.
*/ */
private int mLastFocusedViewId = View.NO_ID; private int mLastFocusedViewId = View.NO_ID;
@ -51,21 +46,17 @@ public class ReactAndroidHWInputDeviceHelper {
this.mReactRootView = mReactRootView; this.mReactRootView = mReactRootView;
} }
/** /** Called from {@link ReactRootView}. This is the main place the key events are handled. */
* Called from {@link ReactRootView}.
* This is the main place the key events are handled.
*/
public void handleKeyEvent(KeyEvent ev) { public void handleKeyEvent(KeyEvent ev) {
int eventKeyCode = ev.getKeyCode(); int eventKeyCode = ev.getKeyCode();
int eventKeyAction = ev.getAction(); int eventKeyAction = ev.getAction();
if ((eventKeyAction == KeyEvent.ACTION_UP || eventKeyAction == KeyEvent.ACTION_DOWN) && KEY_EVENTS_ACTIONS.containsKey(eventKeyCode)) { if ((eventKeyAction == KeyEvent.ACTION_UP || eventKeyAction == KeyEvent.ACTION_DOWN)
&& KEY_EVENTS_ACTIONS.containsKey(eventKeyCode)) {
dispatchEvent(KEY_EVENTS_ACTIONS.get(eventKeyCode), mLastFocusedViewId, eventKeyAction); dispatchEvent(KEY_EVENTS_ACTIONS.get(eventKeyCode), mLastFocusedViewId, eventKeyAction);
} }
} }
/** /** Called from {@link ReactRootView} when focused view changes. */
* Called from {@link ReactRootView} when focused view changes.
*/
public void onFocusChanged(View newFocusedView) { public void onFocusChanged(View newFocusedView) {
if (mLastFocusedViewId == newFocusedView.getId()) { if (mLastFocusedViewId == newFocusedView.getId()) {
return; return;
@ -77,9 +68,7 @@ public class ReactAndroidHWInputDeviceHelper {
dispatchEvent("focus", newFocusedView.getId()); dispatchEvent("focus", newFocusedView.getId());
} }
/** /** Called from {@link ReactRootView} when the whole view hierarchy looses focus. */
* Called from {@link ReactRootView} when the whole view hierarchy looses focus.
*/
public void clearFocus() { public void clearFocus() {
if (mLastFocusedViewId != View.NO_ID) { if (mLastFocusedViewId != View.NO_ID) {
dispatchEvent("blur", mLastFocusedViewId); dispatchEvent("blur", mLastFocusedViewId);

Просмотреть файл

@ -1,16 +1,13 @@
/** /**
* Copyright (c) Facebook, Inc. and its affiliates. * Copyright (c) Facebook, Inc. and its affiliates.
* *
* This source code is licensed under the MIT license found in the * <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* LICENSE file in the root directory of this source tree. * directory of this source tree.
*/ */
package com.facebook.react; package com.facebook.react;
public interface ReactApplication { public interface ReactApplication {
/** /** Get the default {@link ReactNativeHost} for this app. */
* Get the default {@link ReactNativeHost} for this app.
*/
ReactNativeHost getReactNativeHost(); ReactNativeHost getReactNativeHost();
} }

Просмотреть файл

@ -1,21 +1,18 @@
/** /**
* Copyright (c) Facebook, Inc. and its affiliates. * Copyright (c) Facebook, Inc. and its affiliates.
* *
* This source code is licensed under the MIT license found in the * <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* LICENSE file in the root directory of this source tree. * directory of this source tree.
*/ */
package com.facebook.react; package com.facebook.react;
import android.app.Activity; import android.app.Activity;
import android.content.Intent; import android.content.Intent;
import android.os.Bundle; import android.os.Bundle;
import android.view.KeyEvent; import android.view.KeyEvent;
import com.facebook.infer.annotation.Assertions; import com.facebook.infer.annotation.Assertions;
import com.facebook.react.devsupport.DoubleTapReloadRecognizer; import com.facebook.react.devsupport.DoubleTapReloadRecognizer;
import com.facebook.react.modules.core.DefaultHardwareBackBtnHandler; import com.facebook.react.modules.core.DefaultHardwareBackBtnHandler;
import javax.annotation.Nullable; import javax.annotation.Nullable;
/** /**
@ -27,19 +24,19 @@ public class ReactDelegate {
private final Activity mActivity; private final Activity mActivity;
private ReactRootView mReactRootView; private ReactRootView mReactRootView;
@Nullable @Nullable private final String mMainComponentName;
private final String mMainComponentName;
@Nullable @Nullable private Bundle mLaunchOptions;
private Bundle mLaunchOptions;
@Nullable @Nullable private DoubleTapReloadRecognizer mDoubleTapReloadRecognizer;
private DoubleTapReloadRecognizer mDoubleTapReloadRecognizer;
private ReactNativeHost mReactNativeHost; private ReactNativeHost mReactNativeHost;
public ReactDelegate(
public ReactDelegate(Activity activity, ReactNativeHost reactNativeHost, @Nullable String appKey, @Nullable Bundle launchOptions) { Activity activity,
ReactNativeHost reactNativeHost,
@Nullable String appKey,
@Nullable Bundle launchOptions) {
mActivity = activity; mActivity = activity;
mMainComponentName = appKey; mMainComponentName = appKey;
mLaunchOptions = launchOptions; mLaunchOptions = launchOptions;
@ -50,9 +47,12 @@ public class ReactDelegate {
public void onHostResume() { public void onHostResume() {
if (getReactNativeHost().hasInstance()) { if (getReactNativeHost().hasInstance()) {
if (mActivity instanceof DefaultHardwareBackBtnHandler) { if (mActivity instanceof DefaultHardwareBackBtnHandler) {
getReactNativeHost().getReactInstanceManager().onHostResume(mActivity, (DefaultHardwareBackBtnHandler) mActivity); getReactNativeHost()
.getReactInstanceManager()
.onHostResume(mActivity, (DefaultHardwareBackBtnHandler) mActivity);
} else { } else {
throw new ClassCastException("Host Activity does not implement DefaultHardwareBackBtnHandler"); throw new ClassCastException(
"Host Activity does not implement DefaultHardwareBackBtnHandler");
} }
} }
} }
@ -81,9 +81,12 @@ public class ReactDelegate {
return false; return false;
} }
public void onActivityResult(int requestCode, int resultCode, Intent data, boolean shouldForwardToReactInstance) { public void onActivityResult(
int requestCode, int resultCode, Intent data, boolean shouldForwardToReactInstance) {
if (getReactNativeHost().hasInstance() && shouldForwardToReactInstance) { if (getReactNativeHost().hasInstance() && shouldForwardToReactInstance) {
getReactNativeHost().getReactInstanceManager().onActivityResult(mActivity, requestCode, resultCode, data); getReactNativeHost()
.getReactInstanceManager()
.onActivityResult(mActivity, requestCode, resultCode, data);
} }
} }
@ -97,26 +100,23 @@ public class ReactDelegate {
} }
mReactRootView = createRootView(); mReactRootView = createRootView();
mReactRootView.startReactApplication( mReactRootView.startReactApplication(
getReactNativeHost().getReactInstanceManager(), getReactNativeHost().getReactInstanceManager(), appKey, mLaunchOptions);
appKey,
mLaunchOptions);
} }
public ReactRootView getReactRootView() { public ReactRootView getReactRootView() {
return mReactRootView; return mReactRootView;
} }
protected ReactRootView createRootView() { protected ReactRootView createRootView() {
return new ReactRootView(mActivity); return new ReactRootView(mActivity);
} }
/** /**
* Handles delegating the {@link Activity#onKeyUp(int, KeyEvent)} method to determine whether * Handles delegating the {@link Activity#onKeyUp(int, KeyEvent)} method to determine whether the
* the application should show the developer menu or should reload the React Application. * application should show the developer menu or should reload the React Application.
* *
* @return true if we consume the event and either shoed the develop menu or reloaded the application. * @return true if we consume the event and either shoed the develop menu or reloaded the
* application.
*/ */
public boolean shouldShowDevMenuOrReload(int keyCode, KeyEvent event) { public boolean shouldShowDevMenuOrReload(int keyCode, KeyEvent event) {
if (getReactNativeHost().hasInstance() && getReactNativeHost().getUseDeveloperSupport()) { if (getReactNativeHost().hasInstance() && getReactNativeHost().getUseDeveloperSupport()) {
@ -124,7 +124,9 @@ public class ReactDelegate {
getReactNativeHost().getReactInstanceManager().showDevOptionsDialog(); getReactNativeHost().getReactInstanceManager().showDevOptionsDialog();
return true; return true;
} }
boolean didDoubleTapR = Assertions.assertNotNull(mDoubleTapReloadRecognizer).didDoubleTapR(keyCode, mActivity.getCurrentFocus()); boolean didDoubleTapR =
Assertions.assertNotNull(mDoubleTapReloadRecognizer)
.didDoubleTapR(keyCode, mActivity.getCurrentFocus());
if (didDoubleTapR) { if (didDoubleTapR) {
getReactNativeHost().getReactInstanceManager().getDevSupportManager().handleReloadJS(); getReactNativeHost().getReactInstanceManager().getDevSupportManager().handleReloadJS();
return true; return true;
@ -133,9 +135,7 @@ public class ReactDelegate {
return false; return false;
} }
/** /** Get the {@link ReactNativeHost} used by this app. */
* Get the {@link ReactNativeHost} used by this app.
*/
private ReactNativeHost getReactNativeHost() { private ReactNativeHost getReactNativeHost() {
return mReactNativeHost; return mReactNativeHost;
} }
@ -143,5 +143,4 @@ public class ReactDelegate {
public ReactInstanceManager getReactInstanceManager() { public ReactInstanceManager getReactInstanceManager() {
return getReactNativeHost().getReactInstanceManager(); return getReactNativeHost().getReactInstanceManager();
} }
} }

Просмотреть файл

@ -1,11 +1,9 @@
/** /**
* Copyright (c) Facebook, Inc. and its affiliates. * Copyright (c) Facebook, Inc. and its affiliates.
* *
* This source code is licensed under the MIT license found in the * <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* LICENSE file in the root directory of this source tree. * directory of this source tree.
*/ */
package com.facebook.react; package com.facebook.react;
import android.annotation.TargetApi; import android.annotation.TargetApi;
@ -17,14 +15,11 @@ import android.view.KeyEvent;
import android.view.LayoutInflater; import android.view.LayoutInflater;
import android.view.View; import android.view.View;
import android.view.ViewGroup; import android.view.ViewGroup;
import androidx.fragment.app.Fragment;
import com.facebook.react.modules.core.PermissionAwareActivity; import com.facebook.react.modules.core.PermissionAwareActivity;
import com.facebook.react.modules.core.PermissionListener; import com.facebook.react.modules.core.PermissionListener;
import javax.annotation.Nullable; import javax.annotation.Nullable;
import androidx.fragment.app.Fragment;
/** /**
* Fragment for creating a React View. This allows the developer to "embed" a React Application * Fragment for creating a React View. This allows the developer to "embed" a React Application
* inside native components such as a Drawer, ViewPager, etc. * inside native components such as a Drawer, ViewPager, etc.
@ -36,9 +31,7 @@ private static final String ARG_LAUNCH_OPTIONS = "arg_launch_options";
private ReactDelegate mReactDelegate; private ReactDelegate mReactDelegate;
@Nullable @Nullable private PermissionListener mPermissionListener;
private PermissionListener mPermissionListener;
public ReactFragment() { public ReactFragment() {
// Required empty public constructor // Required empty public constructor
@ -70,23 +63,24 @@ public void onCreate(Bundle savedInstanceState) {
if (mainComponentName == null) { if (mainComponentName == null) {
throw new IllegalStateException("Cannot loadApp if component name is null"); throw new IllegalStateException("Cannot loadApp if component name is null");
} }
mReactDelegate = new ReactDelegate(getActivity(), getReactNativeHost(), mainComponentName, launchOptions); mReactDelegate =
new ReactDelegate(getActivity(), getReactNativeHost(), mainComponentName, launchOptions);
} }
/** /**
* Get the {@link ReactNativeHost} used by this app. By default, assumes * Get the {@link ReactNativeHost} used by this app. By default, assumes {@link
* {@link Activity#getApplication()} is an instance of {@link ReactApplication} and calls * Activity#getApplication()} is an instance of {@link ReactApplication} and calls {@link
* {@link ReactApplication#getReactNativeHost()}. Override this method if your application class * ReactApplication#getReactNativeHost()}. Override this method if your application class does not
* does not implement {@code ReactApplication} or you simply have a different mechanism for * implement {@code ReactApplication} or you simply have a different mechanism for storing a
* storing a {@code ReactNativeHost}, e.g. as a static field somewhere. * {@code ReactNativeHost}, e.g. as a static field somewhere.
*/ */
protected ReactNativeHost getReactNativeHost() { protected ReactNativeHost getReactNativeHost() {
return ((ReactApplication) getActivity().getApplication()).getReactNativeHost(); return ((ReactApplication) getActivity().getApplication()).getReactNativeHost();
} }
@Override @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, public View onCreateView(
Bundle savedInstanceState) { LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mReactDelegate.loadApp(); mReactDelegate.loadApp();
return mReactDelegate.getReactRootView(); return mReactDelegate.getReactRootView();
} }
@ -119,18 +113,17 @@ public void onActivityResult(int requestCode, int resultCode, Intent data) {
/** /**
* Helper to forward hardware back presses to our React Native Host * Helper to forward hardware back presses to our React Native Host
* *
* This must be called via a forward from your host Activity * <p>This must be called via a forward from your host Activity
*
*/ */
public boolean onBackPressed() { public boolean onBackPressed() {
return mReactDelegate.onBackPressed(); return mReactDelegate.onBackPressed();
} }
/** /**
* Helper to forward onKeyUp commands from our host Activity. * Helper to forward onKeyUp commands from our host Activity. This allows ReactFragment to handle
* This allows ReactFragment to handle double tap reloads and dev menus * double tap reloads and dev menus
* *
* This must be called via a forward from your host Activity * <p>This must be called via a forward from your host Activity
* *
* @param keyCode keyCode * @param keyCode keyCode
* @param event event * @param event event
@ -141,10 +134,11 @@ public boolean onKeyUp(int keyCode, KeyEvent event) {
} }
@Override @Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { public void onRequestPermissionsResult(
int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults); super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (mPermissionListener != null && if (mPermissionListener != null
mPermissionListener.onRequestPermissionsResult(requestCode, permissions, grantResults)) { && mPermissionListener.onRequestPermissionsResult(requestCode, permissions, grantResults)) {
mPermissionListener = null; mPermissionListener = null;
} }
} }
@ -162,14 +156,13 @@ public int checkSelfPermission(String permission) {
@TargetApi(Build.VERSION_CODES.M) @TargetApi(Build.VERSION_CODES.M)
@Override @Override
public void requestPermissions(String[] permissions, int requestCode, PermissionListener listener) { public void requestPermissions(
String[] permissions, int requestCode, PermissionListener listener) {
mPermissionListener = listener; mPermissionListener = listener;
requestPermissions(permissions, requestCode); requestPermissions(permissions, requestCode);
} }
/** /** Builder class to help instantiate a ReactFragment */
* Builder class to help instantiate a ReactFragment
*/
public static class Builder { public static class Builder {
String mComponentName; String mComponentName;
@ -205,6 +198,5 @@ public static class Builder {
public ReactFragment build() { public ReactFragment build() {
return ReactFragment.newInstance(mComponentName, mLaunchOptions); return ReactFragment.newInstance(mComponentName, mLaunchOptions);
} }
} }
} }

Просмотреть файл

@ -1,17 +1,14 @@
/** /**
* Copyright (c) Facebook, Inc. and its affiliates. * Copyright (c) Facebook, Inc. and its affiliates.
* *
* This source code is licensed under the MIT license found in the * <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* LICENSE file in the root directory of this source tree. * directory of this source tree.
*/ */
package com.facebook.react; package com.facebook.react;
/** /**
* @deprecated * @deprecated ReactFragmentActivity will be removed in 0.59 release. Use {@link ReactActivity}
* ReactFragmentActivity will be removed in 0.59 release. * instead.
* Use {@link ReactActivity} instead.
*/ */
@Deprecated @Deprecated
public abstract class ReactFragmentActivity extends ReactActivity { public abstract class ReactFragmentActivity extends ReactActivity {}
}

Просмотреть файл

@ -1,10 +1,9 @@
/** /**
* Copyright (c) Facebook, Inc. and its affiliates. * Copyright (c) Facebook, Inc. and its affiliates.
* *
* This source code is licensed under the MIT license found in the * <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* LICENSE file in the root directory of this source tree. * directory of this source tree.
*/ */
package com.facebook.react; package com.facebook.react;
import static com.facebook.infer.annotation.ThreadConfined.UI; import static com.facebook.infer.annotation.ThreadConfined.UI;
@ -12,6 +11,7 @@ import static com.facebook.react.bridge.ReactMarkerConstants.ATTACH_MEASURED_ROO
import static com.facebook.react.bridge.ReactMarkerConstants.ATTACH_MEASURED_ROOT_VIEWS_START; import static com.facebook.react.bridge.ReactMarkerConstants.ATTACH_MEASURED_ROOT_VIEWS_START;
import static com.facebook.react.bridge.ReactMarkerConstants.BUILD_NATIVE_MODULE_REGISTRY_END; import static com.facebook.react.bridge.ReactMarkerConstants.BUILD_NATIVE_MODULE_REGISTRY_END;
import static com.facebook.react.bridge.ReactMarkerConstants.BUILD_NATIVE_MODULE_REGISTRY_START; import static com.facebook.react.bridge.ReactMarkerConstants.BUILD_NATIVE_MODULE_REGISTRY_START;
import static com.facebook.react.bridge.ReactMarkerConstants.CHANGE_THREAD_PRIORITY;
import static com.facebook.react.bridge.ReactMarkerConstants.CREATE_CATALYST_INSTANCE_END; import static com.facebook.react.bridge.ReactMarkerConstants.CREATE_CATALYST_INSTANCE_END;
import static com.facebook.react.bridge.ReactMarkerConstants.CREATE_CATALYST_INSTANCE_START; import static com.facebook.react.bridge.ReactMarkerConstants.CREATE_CATALYST_INSTANCE_START;
import static com.facebook.react.bridge.ReactMarkerConstants.CREATE_REACT_CONTEXT_START; import static com.facebook.react.bridge.ReactMarkerConstants.CREATE_REACT_CONTEXT_START;
@ -25,7 +25,6 @@ import static com.facebook.react.bridge.ReactMarkerConstants.REACT_CONTEXT_THREA
import static com.facebook.react.bridge.ReactMarkerConstants.REACT_CONTEXT_THREAD_START; import static com.facebook.react.bridge.ReactMarkerConstants.REACT_CONTEXT_THREAD_START;
import static com.facebook.react.bridge.ReactMarkerConstants.SETUP_REACT_CONTEXT_END; import static com.facebook.react.bridge.ReactMarkerConstants.SETUP_REACT_CONTEXT_END;
import static com.facebook.react.bridge.ReactMarkerConstants.SETUP_REACT_CONTEXT_START; import static com.facebook.react.bridge.ReactMarkerConstants.SETUP_REACT_CONTEXT_START;
import static com.facebook.react.bridge.ReactMarkerConstants.CHANGE_THREAD_PRIORITY;
import static com.facebook.react.bridge.ReactMarkerConstants.VM_INIT; import static com.facebook.react.bridge.ReactMarkerConstants.VM_INIT;
import static com.facebook.react.uimanager.common.UIManagerType.FABRIC; import static com.facebook.react.uimanager.common.UIManagerType.FABRIC;
import static com.facebook.systrace.Systrace.TRACE_TAG_REACT_APPS; import static com.facebook.systrace.Systrace.TRACE_TAG_REACT_APPS;
@ -38,9 +37,9 @@ import android.content.Intent;
import android.net.Uri; import android.net.Uri;
import android.os.Bundle; import android.os.Bundle;
import android.os.Process; import android.os.Process;
import androidx.core.view.ViewCompat;
import android.util.Log; import android.util.Log;
import android.view.View; import android.view.View;
import androidx.core.view.ViewCompat;
import com.facebook.common.logging.FLog; import com.facebook.common.logging.FLog;
import com.facebook.debug.holder.PrinterHolder; import com.facebook.debug.holder.PrinterHolder;
import com.facebook.debug.tags.ReactDebugOverlayTags; import com.facebook.debug.tags.ReactDebugOverlayTags;
@ -107,28 +106,26 @@ import javax.annotation.Nullable;
/** /**
* This class is managing instances of {@link CatalystInstance}. It exposes a way to configure * This class is managing instances of {@link CatalystInstance}. It exposes a way to configure
* catalyst instance using {@link ReactPackage} and keeps track of the lifecycle of that * catalyst instance using {@link ReactPackage} and keeps track of the lifecycle of that instance.
* instance. It also sets up connection between the instance and developers support functionality * It also sets up connection between the instance and developers support functionality of the
* of the framework. * framework.
* *
* An instance of this manager is required to start JS application in {@link ReactRootView} (see * <p>An instance of this manager is required to start JS application in {@link ReactRootView} (see
* {@link ReactRootView#startReactApplication} for more info). * {@link ReactRootView#startReactApplication} for more info).
* *
* The lifecycle of the instance of {@link ReactInstanceManager} should be bound to the * <p>The lifecycle of the instance of {@link ReactInstanceManager} should be bound to the activity
* activity that owns the {@link ReactRootView} that is used to render react application using this * that owns the {@link ReactRootView} that is used to render react application using this instance
* instance manager (see {@link ReactRootView#startReactApplication}). It's required to pass owning * manager (see {@link ReactRootView#startReactApplication}). It's required to pass owning
* activity's lifecycle events to the instance manager (see {@link #onHostPause}, {@link * activity's lifecycle events to the instance manager (see {@link #onHostPause}, {@link
* #onHostDestroy} and {@link #onHostResume}). * #onHostDestroy} and {@link #onHostResume}).
* *
* To instantiate an instance of this class use {@link #builder}. * <p>To instantiate an instance of this class use {@link #builder}.
*/ */
@ThreadSafe @ThreadSafe
public class ReactInstanceManager { public class ReactInstanceManager {
private static final String TAG = ReactInstanceManager.class.getSimpleName(); private static final String TAG = ReactInstanceManager.class.getSimpleName();
/** /** Listener interface for react instance events. */
* Listener interface for react instance events.
*/
public interface ReactInstanceEventListener { public interface ReactInstanceEventListener {
/** /**
@ -138,8 +135,8 @@ public class ReactInstanceManager {
void onReactContextInitialized(ReactContext context); void onReactContextInitialized(ReactContext context);
} }
private final Set<ReactRoot> mAttachedReactRoots = Collections.synchronizedSet( private final Set<ReactRoot> mAttachedReactRoots =
new HashSet<ReactRoot>()); Collections.synchronizedSet(new HashSet<ReactRoot>());
private volatile LifecycleState mLifecycleState; private volatile LifecycleState mLifecycleState;
@ -176,8 +173,7 @@ public class ReactInstanceManager {
private final JSBundleLoader mJsBundleLoader; private final JSBundleLoader mJsBundleLoader;
public ReactContextInitParams( public ReactContextInitParams(
JavaScriptExecutorFactory jsExecutorFactory, JavaScriptExecutorFactory jsExecutorFactory, JSBundleLoader jsBundleLoader) {
JSBundleLoader jsBundleLoader) {
mJsExecutorFactory = Assertions.assertNotNull(jsExecutorFactory); mJsExecutorFactory = Assertions.assertNotNull(jsExecutorFactory);
mJsBundleLoader = Assertions.assertNotNull(jsBundleLoader); mJsBundleLoader = Assertions.assertNotNull(jsBundleLoader);
} }
@ -191,9 +187,7 @@ public class ReactInstanceManager {
} }
} }
/** /** Creates a builder that is capable of creating an instance of {@link ReactInstanceManager}. */
* Creates a builder that is capable of creating an instance of {@link ReactInstanceManager}.
*/
public static ReactInstanceManagerBuilder builder() { public static ReactInstanceManagerBuilder builder() {
return new ReactInstanceManagerBuilder(); return new ReactInstanceManagerBuilder();
} }
@ -326,10 +320,10 @@ public class ReactInstanceManager {
/** /**
* Trigger react context initialization asynchronously in a background async task. This enables * Trigger react context initialization asynchronously in a background async task. This enables
* applications to pre-load the application JS, and execute global code before * applications to pre-load the application JS, and execute global code before {@link
* {@link ReactRootView} is available and measured. * ReactRootView} is available and measured.
* *
* Called from UI thread. * <p>Called from UI thread.
*/ */
@ThreadConfined(UI) @ThreadConfined(UI)
public void createReactContextInBackground() { public void createReactContextInBackground() {
@ -351,8 +345,8 @@ public class ReactInstanceManager {
public void recreateReactContextInBackground() { public void recreateReactContextInBackground() {
Assertions.assertCondition( Assertions.assertCondition(
mHasStartedCreatingInitialContext, mHasStartedCreatingInitialContext,
"recreateReactContextInBackground should only be called after the initial " + "recreateReactContextInBackground should only be called after the initial "
"createReactContextInBackground call."); + "createReactContextInBackground call.");
recreateReactContextInBackgroundInner(); recreateReactContextInBackgroundInner();
} }
@ -367,8 +361,8 @@ public class ReactInstanceManager {
final DeveloperSettings devSettings = mDevSupportManager.getDevSettings(); final DeveloperSettings devSettings = mDevSupportManager.getDevSettings();
// If remote JS debugging is enabled, load from dev server. // If remote JS debugging is enabled, load from dev server.
if (mDevSupportManager.hasUpToDateJSBundleInCache() && if (mDevSupportManager.hasUpToDateJSBundleInCache()
!devSettings.isRemoteJSDebugEnabled()) { && !devSettings.isRemoteJSDebugEnabled()) {
// If there is a up-to-date bundle downloaded from server, // If there is a up-to-date bundle downloaded from server,
// with remote JS debugging disabled, always use that. // with remote JS debugging disabled, always use that.
onJSBundleLoadedFromServer(null); onJSBundleLoadedFromServer(null);
@ -449,9 +443,7 @@ public class ReactInstanceManager {
} }
} }
/** /** This method will give JS the opportunity to receive intents via Linking. */
* This method will give JS the opportunity to receive intents via Linking.
*/
@ThreadConfined(UI) @ThreadConfined(UI)
public void onNewIntent(Intent intent) { public void onNewIntent(Intent intent) {
UiThreadUtil.assertOnUiThread(); UiThreadUtil.assertOnUiThread();
@ -501,8 +493,8 @@ public class ReactInstanceManager {
/** /**
* Call this from {@link Activity#onPause()}. This notifies any listening modules so they can do * Call this from {@link Activity#onPause()}. This notifies any listening modules so they can do
* any necessary cleanup. The passed Activity is the current Activity being paused. This will * any necessary cleanup. The passed Activity is the current Activity being paused. This will
* always be the foreground activity that would be returned by * always be the foreground activity that would be returned by {@link
* {@link ReactContext#getCurrentActivity()}. * ReactContext#getCurrentActivity()}.
* *
* @param activity the activity being paused * @param activity the activity being paused
*/ */
@ -511,19 +503,22 @@ public class ReactInstanceManager {
Assertions.assertNotNull(mCurrentActivity); Assertions.assertNotNull(mCurrentActivity);
Assertions.assertCondition( Assertions.assertCondition(
activity == mCurrentActivity, activity == mCurrentActivity,
"Pausing an activity that is not the current activity, this is incorrect! " + "Pausing an activity that is not the current activity, this is incorrect! "
"Current activity: " + mCurrentActivity.getClass().getSimpleName() + " " + + "Current activity: "
"Paused activity: " + activity.getClass().getSimpleName()); + mCurrentActivity.getClass().getSimpleName()
+ " "
+ "Paused activity: "
+ activity.getClass().getSimpleName());
onHostPause(); onHostPause();
} }
/** /**
* Use this method when the activity resumes to enable invoking the back button directly from JS. * Use this method when the activity resumes to enable invoking the back button directly from JS.
* *
* This method retains an instance to provided mDefaultBackButtonImpl. Thus it's important to pass * <p>This method retains an instance to provided mDefaultBackButtonImpl. Thus it's important to
* from the activity instance that owns this particular instance of {@link * pass from the activity instance that owns this particular instance of {@link
* ReactInstanceManager}, so that once this instance receive {@link #onHostDestroy} event it * ReactInstanceManager}, so that once this instance receive {@link #onHostDestroy} event it will
* will clear the reference to that defaultBackButtonImpl. * clear the reference to that defaultBackButtonImpl.
* *
* @param defaultBackButtonImpl a {@link DefaultHardwareBackBtnHandler} from an Activity that owns * @param defaultBackButtonImpl a {@link DefaultHardwareBackBtnHandler} from an Activity that owns
* this instance of {@link ReactInstanceManager}. * this instance of {@link ReactInstanceManager}.
@ -536,9 +531,7 @@ public class ReactInstanceManager {
onHostResume(activity); onHostResume(activity);
} }
/** /** Use this method when the activity resumes. */
* Use this method when the activity resumes.
*/
@ThreadConfined(UI) @ThreadConfined(UI)
public void onHostResume(Activity activity) { public void onHostResume(Activity activity) {
UiThreadUtil.assertOnUiThread(); UiThreadUtil.assertOnUiThread();
@ -558,7 +551,8 @@ public class ReactInstanceManager {
// We check if activity is attached to window by checking if decor view is attached // We check if activity is attached to window by checking if decor view is attached
final View decorView = mCurrentActivity.getWindow().getDecorView(); final View decorView = mCurrentActivity.getWindow().getDecorView();
if (!ViewCompat.isAttachedToWindow(decorView)) { if (!ViewCompat.isAttachedToWindow(decorView)) {
decorView.addOnAttachStateChangeListener(new View.OnAttachStateChangeListener() { decorView.addOnAttachStateChangeListener(
new View.OnAttachStateChangeListener() {
@Override @Override
public void onViewAttachedToWindow(View v) { public void onViewAttachedToWindow(View v) {
// we can drop listener now that we know the view is attached // we can drop listener now that we know the view is attached
@ -612,9 +606,7 @@ public class ReactInstanceManager {
} }
} }
/** /** Destroy this React instance and the attached JS context. */
* Destroy this React instance and the attached JS context.
*/
@ThreadConfined(UI) @ThreadConfined(UI)
public void destroy() { public void destroy() {
UiThreadUtil.assertOnUiThread(); UiThreadUtil.assertOnUiThread();
@ -655,9 +647,9 @@ public class ReactInstanceManager {
ReactContext currentContext = getCurrentReactContext(); ReactContext currentContext = getCurrentReactContext();
if (currentContext != null) { if (currentContext != null) {
// we currently don't have an onCreate callback so we call onResume for both transitions // we currently don't have an onCreate callback so we call onResume for both transitions
if (force || if (force
mLifecycleState == LifecycleState.BEFORE_RESUME || || mLifecycleState == LifecycleState.BEFORE_RESUME
mLifecycleState == LifecycleState.BEFORE_CREATE) { || mLifecycleState == LifecycleState.BEFORE_CREATE) {
currentContext.onHostResume(mCurrentActivity); currentContext.onHostResume(mCurrentActivity);
} }
} }
@ -729,9 +721,9 @@ public class ReactInstanceManager {
* Attach given {@param reactRoot} to a catalyst instance manager and start JS application using * Attach given {@param reactRoot} to a catalyst instance manager and start JS application using
* JS module provided by {@link ReactRootView#getJSModuleName}. If the react context is currently * JS module provided by {@link ReactRootView#getJSModuleName}. If the react context is currently
* being (re)-created, or if react context has not been created yet, the JS application associated * being (re)-created, or if react context has not been created yet, the JS application associated
* with the provided reactRoot reactRoot will be started asynchronously, i.e this method won't block. * with the provided reactRoot reactRoot will be started asynchronously, i.e this method won't
* This reactRoot will then be tracked by this manager and in case of catalyst instance restart it will * block. This reactRoot will then be tracked by this manager and in case of catalyst instance
* be re-attached. * restart it will be re-attached.
*/ */
@ThreadConfined(UI) @ThreadConfined(UI)
public void attachRootView(ReactRoot reactRoot) { public void attachRootView(ReactRoot reactRoot) {
@ -742,7 +734,8 @@ public class ReactInstanceManager {
clearReactRoot(reactRoot); clearReactRoot(reactRoot);
// If react context is being created in the background, JS application will be started // If react context is being created in the background, JS application will be started
// automatically when creation completes, as reactRoot reactRoot is part of the attached reactRoot reactRoot list. // automatically when creation completes, as reactRoot reactRoot is part of the attached
// reactRoot reactRoot list.
ReactContext currentContext = getCurrentReactContext(); ReactContext currentContext = getCurrentReactContext();
if (mCreateReactContextThread == null && currentContext != null) { if (mCreateReactContextThread == null && currentContext != null) {
attachRootViewToInstance(reactRoot); attachRootViewToInstance(reactRoot);
@ -768,9 +761,7 @@ public class ReactInstanceManager {
} }
} }
/** /** Uses configured {@link ReactPackage} instances to create all view managers. */
* Uses configured {@link ReactPackage} instances to create all view managers.
*/
public List<ViewManager> getOrCreateViewManagers( public List<ViewManager> getOrCreateViewManagers(
ReactApplicationContext catalystApplicationContext) { ReactApplicationContext catalystApplicationContext) {
ReactMarker.logMarker(CREATE_VIEW_MANAGERS_START); ReactMarker.logMarker(CREATE_VIEW_MANAGERS_START);
@ -831,7 +822,8 @@ public class ReactInstanceManager {
synchronized (mPackages) { synchronized (mPackages) {
Set<String> uniqueNames = new HashSet<>(); Set<String> uniqueNames = new HashSet<>();
for (ReactPackage reactPackage : mPackages) { for (ReactPackage reactPackage : mPackages) {
SystraceMessage.beginSection(TRACE_TAG_REACT_JAVA_BRIDGE, "ReactInstanceManager.getViewManagerName") SystraceMessage.beginSection(
TRACE_TAG_REACT_JAVA_BRIDGE, "ReactInstanceManager.getViewManagerName")
.arg("Package", reactPackage.getClass().getSimpleName()) .arg("Package", reactPackage.getClass().getSimpleName())
.flush(); .flush();
if (reactPackage instanceof ViewManagerOnDemandReactPackage) { if (reactPackage instanceof ViewManagerOnDemandReactPackage) {
@ -848,16 +840,12 @@ public class ReactInstanceManager {
} }
} }
/** /** Add a listener to be notified of react instance events. */
* Add a listener to be notified of react instance events.
*/
public void addReactInstanceEventListener(ReactInstanceEventListener listener) { public void addReactInstanceEventListener(ReactInstanceEventListener listener) {
mReactInstanceEventListeners.add(listener); mReactInstanceEventListeners.add(listener);
} }
/** /** Remove a listener previously added with {@link #addReactInstanceEventListener}. */
* Remove a listener previously added with {@link #addReactInstanceEventListener}.
*/
public void removeReactInstanceEventListener(ReactInstanceEventListener listener) { public void removeReactInstanceEventListener(ReactInstanceEventListener listener) {
mReactInstanceEventListeners.remove(listener); mReactInstanceEventListeners.remove(listener);
} }
@ -891,10 +879,10 @@ public class ReactInstanceManager {
private void onJSBundleLoadedFromServer(@Nullable NativeDeltaClient nativeDeltaClient) { private void onJSBundleLoadedFromServer(@Nullable NativeDeltaClient nativeDeltaClient) {
Log.d(ReactConstants.TAG, "ReactInstanceManager.onJSBundleLoadedFromServer()"); Log.d(ReactConstants.TAG, "ReactInstanceManager.onJSBundleLoadedFromServer()");
JSBundleLoader bundleLoader = nativeDeltaClient == null JSBundleLoader bundleLoader =
nativeDeltaClient == null
? JSBundleLoader.createCachedBundleFromNetworkLoader( ? JSBundleLoader.createCachedBundleFromNetworkLoader(
mDevSupportManager.getSourceUrl(), mDevSupportManager.getSourceUrl(), mDevSupportManager.getDownloadedJSBundleFile())
mDevSupportManager.getDownloadedJSBundleFile())
: JSBundleLoader.createDeltaFromNetworkLoader( : JSBundleLoader.createDeltaFromNetworkLoader(
mDevSupportManager.getSourceUrl(), nativeDeltaClient); mDevSupportManager.getSourceUrl(), nativeDeltaClient);
@ -903,14 +891,12 @@ public class ReactInstanceManager {
@ThreadConfined(UI) @ThreadConfined(UI)
private void recreateReactContextInBackground( private void recreateReactContextInBackground(
JavaScriptExecutorFactory jsExecutorFactory, JavaScriptExecutorFactory jsExecutorFactory, JSBundleLoader jsBundleLoader) {
JSBundleLoader jsBundleLoader) {
Log.d(ReactConstants.TAG, "ReactInstanceManager.recreateReactContextInBackground()"); Log.d(ReactConstants.TAG, "ReactInstanceManager.recreateReactContextInBackground()");
UiThreadUtil.assertOnUiThread(); UiThreadUtil.assertOnUiThread();
final ReactContextInitParams initParams = new ReactContextInitParams( final ReactContextInitParams initParams =
jsExecutorFactory, new ReactContextInitParams(jsExecutorFactory, jsBundleLoader);
jsBundleLoader);
if (mCreateReactContextThread == null) { if (mCreateReactContextThread == null) {
runCreateReactContextOnNewThread(initParams); runCreateReactContextOnNewThread(initParams);
} else { } else {
@ -947,7 +933,8 @@ public class ReactInstanceManager {
} }
} }
} }
// As destroy() may have run and set this to false, ensure that it is true before we create // As destroy() may have run and set this to false, ensure that it is true before we
// create
mHasStartedCreatingInitialContext = true; mHasStartedCreatingInitialContext = true;
try { try {
@ -1009,7 +996,6 @@ public class ReactInstanceManager {
catalystInstance.initialize(); catalystInstance.initialize();
mDevSupportManager.onNewReactContextCreated(reactContext); mDevSupportManager.onNewReactContextCreated(reactContext);
mMemoryPressureRouter.addMemoryPressureListener(catalystInstance); mMemoryPressureRouter.addMemoryPressureListener(catalystInstance);
moveReactContextToCurrentLifecycleState(); moveReactContextToCurrentLifecycleState();
@ -1057,28 +1043,30 @@ public class ReactInstanceManager {
private void attachRootViewToInstance(final ReactRoot reactRoot) { private void attachRootViewToInstance(final ReactRoot reactRoot) {
Log.d(ReactConstants.TAG, "ReactInstanceManager.attachRootViewToInstance()"); Log.d(ReactConstants.TAG, "ReactInstanceManager.attachRootViewToInstance()");
Systrace.beginSection(TRACE_TAG_REACT_JAVA_BRIDGE, "attachRootViewToInstance"); Systrace.beginSection(TRACE_TAG_REACT_JAVA_BRIDGE, "attachRootViewToInstance");
UIManager uiManager = UIManagerHelper.getUIManager(mCurrentReactContext, reactRoot.getUIManagerType()); UIManager uiManager =
UIManagerHelper.getUIManager(mCurrentReactContext, reactRoot.getUIManagerType());
@Nullable Bundle initialProperties = reactRoot.getAppProperties(); @Nullable Bundle initialProperties = reactRoot.getAppProperties();
final int rootTag = uiManager.addRootView( final int rootTag =
uiManager.addRootView(
reactRoot.getRootViewGroup(), reactRoot.getRootViewGroup(),
initialProperties == null ? initialProperties == null
new WritableNativeMap() : Arguments.fromBundle(initialProperties), ? new WritableNativeMap()
: Arguments.fromBundle(initialProperties),
reactRoot.getInitialUITemplate()); reactRoot.getInitialUITemplate());
reactRoot.setRootViewTag(rootTag); reactRoot.setRootViewTag(rootTag);
if (reactRoot.getUIManagerType() == FABRIC) { if (reactRoot.getUIManagerType() == FABRIC) {
// Fabric requires to call updateRootLayoutSpecs before starting JS Application, // Fabric requires to call updateRootLayoutSpecs before starting JS Application,
// this ensures the root will hace the correct pointScaleFactor. // this ensures the root will hace the correct pointScaleFactor.
uiManager.updateRootLayoutSpecs(rootTag, reactRoot.getWidthMeasureSpec(), reactRoot.getHeightMeasureSpec()); uiManager.updateRootLayoutSpecs(
rootTag, reactRoot.getWidthMeasureSpec(), reactRoot.getHeightMeasureSpec());
reactRoot.setShouldLogContentAppeared(true); reactRoot.setShouldLogContentAppeared(true);
} else { } else {
reactRoot.runApplication(); reactRoot.runApplication();
} }
Systrace.beginAsyncSection( Systrace.beginAsyncSection(
TRACE_TAG_REACT_JAVA_BRIDGE, TRACE_TAG_REACT_JAVA_BRIDGE, "pre_rootView.onAttachedToReactInstance", rootTag);
"pre_rootView.onAttachedToReactInstance",
rootTag);
UiThreadUtil.runOnUiThread( UiThreadUtil.runOnUiThread(
new Runnable() { new Runnable() {
@Override @Override
@ -1091,19 +1079,18 @@ public class ReactInstanceManager {
Systrace.endSection(TRACE_TAG_REACT_JAVA_BRIDGE); Systrace.endSection(TRACE_TAG_REACT_JAVA_BRIDGE);
} }
private void detachViewFromInstance( private void detachViewFromInstance(ReactRoot reactRoot, CatalystInstance catalystInstance) {
ReactRoot reactRoot,
CatalystInstance catalystInstance) {
Log.d(ReactConstants.TAG, "ReactInstanceManager.detachViewFromInstance()"); Log.d(ReactConstants.TAG, "ReactInstanceManager.detachViewFromInstance()");
UiThreadUtil.assertOnUiThread(); UiThreadUtil.assertOnUiThread();
if (reactRoot.getUIManagerType() == FABRIC) { if (reactRoot.getUIManagerType() == FABRIC) {
catalystInstance.getJSModule(ReactFabric.class) catalystInstance
.getJSModule(ReactFabric.class)
.unmountComponentAtNode(reactRoot.getRootViewTag()); .unmountComponentAtNode(reactRoot.getRootViewTag());
} else { } else {
catalystInstance.getJSModule(AppRegistry.class) catalystInstance
.getJSModule(AppRegistry.class)
.unmountApplicationComponentAtRootTag(reactRoot.getRootViewTag()); .unmountApplicationComponentAtRootTag(reactRoot.getRootViewTag());
} }
} }
private void tearDownReactContext(ReactContext reactContext) { private void tearDownReactContext(ReactContext reactContext) {
@ -1124,24 +1111,23 @@ public class ReactInstanceManager {
mMemoryPressureRouter.removeMemoryPressureListener(reactContext.getCatalystInstance()); mMemoryPressureRouter.removeMemoryPressureListener(reactContext.getCatalystInstance());
} }
/** /** @return instance of {@link ReactContext} configured a {@link CatalystInstance} set */
* @return instance of {@link ReactContext} configured a {@link CatalystInstance} set
*/
private ReactApplicationContext createReactContext( private ReactApplicationContext createReactContext(
JavaScriptExecutor jsExecutor, JavaScriptExecutor jsExecutor, JSBundleLoader jsBundleLoader) {
JSBundleLoader jsBundleLoader) {
Log.d(ReactConstants.TAG, "ReactInstanceManager.createReactContext()"); Log.d(ReactConstants.TAG, "ReactInstanceManager.createReactContext()");
ReactMarker.logMarker(CREATE_REACT_CONTEXT_START, jsExecutor.getName()); ReactMarker.logMarker(CREATE_REACT_CONTEXT_START, jsExecutor.getName());
final ReactApplicationContext reactContext = new ReactApplicationContext(mApplicationContext); final ReactApplicationContext reactContext = new ReactApplicationContext(mApplicationContext);
NativeModuleCallExceptionHandler exceptionHandler = mNativeModuleCallExceptionHandler != null NativeModuleCallExceptionHandler exceptionHandler =
mNativeModuleCallExceptionHandler != null
? mNativeModuleCallExceptionHandler ? mNativeModuleCallExceptionHandler
: mDevSupportManager; : mDevSupportManager;
reactContext.setNativeModuleCallExceptionHandler(exceptionHandler); reactContext.setNativeModuleCallExceptionHandler(exceptionHandler);
NativeModuleRegistry nativeModuleRegistry = processPackages(reactContext, mPackages, false); NativeModuleRegistry nativeModuleRegistry = processPackages(reactContext, mPackages, false);
CatalystInstanceImpl.Builder catalystInstanceBuilder = new CatalystInstanceImpl.Builder() CatalystInstanceImpl.Builder catalystInstanceBuilder =
new CatalystInstanceImpl.Builder()
.setReactQueueConfigurationSpec(ReactQueueConfigurationSpec.createDefault()) .setReactQueueConfigurationSpec(ReactQueueConfigurationSpec.createDefault())
.setJSExecutor(jsExecutor) .setJSExecutor(jsExecutor)
.setRegistry(nativeModuleRegistry) .setRegistry(nativeModuleRegistry)
@ -1162,11 +1148,13 @@ public class ReactInstanceManager {
reactContext.initializeWithInstance(catalystInstance); reactContext.initializeWithInstance(catalystInstance);
if (mJSIModulePackage != null) { if (mJSIModulePackage != null) {
catalystInstance.addJSIModules(mJSIModulePackage catalystInstance.addJSIModules(
.getJSIModules(reactContext, catalystInstance.getJavaScriptContextHolder())); mJSIModulePackage.getJSIModules(
reactContext, catalystInstance.getJavaScriptContextHolder()));
if (ReactFeatureFlags.useTurboModules) { if (ReactFeatureFlags.useTurboModules) {
catalystInstance.setTurboModuleManager(catalystInstance.getJSIModule(JSIModuleType.TurboModuleManager)); catalystInstance.setTurboModuleManager(
catalystInstance.getJSIModule(JSIModuleType.TurboModuleManager));
} }
} }
if (mBridgeIdleDebugListener != null) { if (mBridgeIdleDebugListener != null) {
@ -1187,9 +1175,8 @@ public class ReactInstanceManager {
ReactApplicationContext reactContext, ReactApplicationContext reactContext,
List<ReactPackage> packages, List<ReactPackage> packages,
boolean checkAndUpdatePackageMembership) { boolean checkAndUpdatePackageMembership) {
NativeModuleRegistryBuilder nativeModuleRegistryBuilder = new NativeModuleRegistryBuilder( NativeModuleRegistryBuilder nativeModuleRegistryBuilder =
reactContext, new NativeModuleRegistryBuilder(reactContext, this);
this);
ReactMarker.logMarker(PROCESS_PACKAGES_START); ReactMarker.logMarker(PROCESS_PACKAGES_START);
@ -1226,8 +1213,7 @@ public class ReactInstanceManager {
} }
private void processPackage( private void processPackage(
ReactPackage reactPackage, ReactPackage reactPackage, NativeModuleRegistryBuilder nativeModuleRegistryBuilder) {
NativeModuleRegistryBuilder nativeModuleRegistryBuilder) {
SystraceMessage.beginSection(TRACE_TAG_REACT_JAVA_BRIDGE, "processPackage") SystraceMessage.beginSection(TRACE_TAG_REACT_JAVA_BRIDGE, "processPackage")
.arg("className", reactPackage.getClass().getSimpleName()) .arg("className", reactPackage.getClass().getSimpleName())
.flush(); .flush();

Просмотреть файл

@ -28,9 +28,7 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import javax.annotation.Nullable; import javax.annotation.Nullable;
/** /** Builder class for {@link ReactInstanceManager} */
* Builder class for {@link ReactInstanceManager}
*/
public class ReactInstanceManagerBuilder { public class ReactInstanceManagerBuilder {
private final List<ReactPackage> mPackages = new ArrayList<>(); private final List<ReactPackage> mPackages = new ArrayList<>();
@ -55,13 +53,9 @@ public class ReactInstanceManagerBuilder {
private @Nullable JSIModulePackage mJSIModulesPackage; private @Nullable JSIModulePackage mJSIModulesPackage;
private @Nullable Map<String, RequestHandler> mCustomPackagerCommandHandlers; private @Nullable Map<String, RequestHandler> mCustomPackagerCommandHandlers;
/* package protected */ ReactInstanceManagerBuilder() { /* package protected */ ReactInstanceManagerBuilder() {}
}
/** /** Sets a provider of {@link UIImplementation}. Uses default provider if null is passed. */
* Sets a provider of {@link UIImplementation}.
* Uses default provider if null is passed.
*/
public ReactInstanceManagerBuilder setUIImplementationProvider( public ReactInstanceManagerBuilder setUIImplementationProvider(
@Nullable UIImplementationProvider uiImplementationProvider) { @Nullable UIImplementationProvider uiImplementationProvider) {
mUIImplementationProvider = uiImplementationProvider; mUIImplementationProvider = uiImplementationProvider;
@ -74,9 +68,7 @@ public class ReactInstanceManagerBuilder {
return this; return this;
} }
/** /** Factory for desired implementation of JavaScriptExecutor. */
* Factory for desired implementation of JavaScriptExecutor.
*/
public ReactInstanceManagerBuilder setJavaScriptExecutorFactory( public ReactInstanceManagerBuilder setJavaScriptExecutorFactory(
@Nullable JavaScriptExecutorFactory javaScriptExecutorFactory) { @Nullable JavaScriptExecutorFactory javaScriptExecutorFactory) {
mJavaScriptExecutorFactory = javaScriptExecutorFactory; mJavaScriptExecutorFactory = javaScriptExecutorFactory;
@ -84,8 +76,8 @@ public class ReactInstanceManagerBuilder {
} }
/** /**
* Name of the JS bundle file to be loaded from application's raw assets. * Name of the JS bundle file to be loaded from application's raw assets. Example: {@code
* Example: {@code "index.android.js"} * "index.android.js"}
*/ */
public ReactInstanceManagerBuilder setBundleAssetName(String bundleAssetName) { public ReactInstanceManagerBuilder setBundleAssetName(String bundleAssetName) {
mJSBundleAssetUrl = (bundleAssetName == null ? null : "assets://" + bundleAssetName); mJSBundleAssetUrl = (bundleAssetName == null ? null : "assets://" + bundleAssetName);
@ -96,7 +88,7 @@ public class ReactInstanceManagerBuilder {
/** /**
* Path to the JS bundle file to be loaded from the file system. * Path to the JS bundle file to be loaded from the file system.
* *
* Example: {@code "assets://index.android.js" or "/sdcard/main.jsbundle"} * <p>Example: {@code "assets://index.android.js" or "/sdcard/main.jsbundle"}
*/ */
public ReactInstanceManagerBuilder setJSBundleFile(String jsBundleFile) { public ReactInstanceManagerBuilder setJSBundleFile(String jsBundleFile) {
if (jsBundleFile.startsWith("assets://")) { if (jsBundleFile.startsWith("assets://")) {
@ -108,10 +100,10 @@ public class ReactInstanceManagerBuilder {
} }
/** /**
* Bundle loader to use when setting up JS environment. This supersedes * Bundle loader to use when setting up JS environment. This supersedes prior invocations of
* prior invocations of {@link setJSBundleFile} and {@link setBundleAssetName}. * {@link setJSBundleFile} and {@link setBundleAssetName}.
* *
* Example: {@code JSBundleLoader.createFileLoader(application, bundleFile)} * <p>Example: {@code JSBundleLoader.createFileLoader(application, bundleFile)}
*/ */
public ReactInstanceManagerBuilder setJSBundleLoader(JSBundleLoader jsBundleLoader) { public ReactInstanceManagerBuilder setJSBundleLoader(JSBundleLoader jsBundleLoader) {
mJSBundleLoader = jsBundleLoader; mJSBundleLoader = jsBundleLoader;
@ -120,12 +112,9 @@ public class ReactInstanceManagerBuilder {
} }
/** /**
* Path to your app's main module on the packager server. This is used when * Path to your app's main module on the packager server. This is used when reloading JS during
* reloading JS during development. All paths are relative to the root folder * development. All paths are relative to the root folder the packager is serving files from.
* the packager is serving files from. * Examples: {@code "index.android"} or {@code "subdirectory/index.android"}
* Examples:
* {@code "index.android"} or
* {@code "subdirectory/index.android"}
*/ */
public ReactInstanceManagerBuilder setJSMainModulePath(String jsMainModulePath) { public ReactInstanceManagerBuilder setJSMainModulePath(String jsMainModulePath) {
mJSMainModulePath = jsMainModulePath; mJSMainModulePath = jsMainModulePath;
@ -148,9 +137,7 @@ public class ReactInstanceManagerBuilder {
return this; return this;
} }
/** /** Required. This must be your {@code Application} instance. */
* Required. This must be your {@code Application} instance.
*/
public ReactInstanceManagerBuilder setApplication(Application application) { public ReactInstanceManagerBuilder setApplication(Application application) {
mApplication = application; mApplication = application;
return this; return this;
@ -168,9 +155,9 @@ public class ReactInstanceManagerBuilder {
} }
/** /**
* When {@code true}, developer options such as JS reloading and debugging are enabled. * When {@code true}, developer options such as JS reloading and debugging are enabled. Note you
* Note you still have to call {@link #showDevOptionsDialog} to show the dev menu, * still have to call {@link #showDevOptionsDialog} to show the dev menu, e.g. when the device
* e.g. when the device Menu button is pressed. * Menu button is pressed.
*/ */
public ReactInstanceManagerBuilder setUseDeveloperSupport(boolean useDeveloperSupport) { public ReactInstanceManagerBuilder setUseDeveloperSupport(boolean useDeveloperSupport) {
mUseDeveloperSupport = useDeveloperSupport; mUseDeveloperSupport = useDeveloperSupport;
@ -188,9 +175,9 @@ public class ReactInstanceManagerBuilder {
} }
/** /**
* Set the exception handler for all native module calls. If not set, the default * Set the exception handler for all native module calls. If not set, the default {@link
* {@link DevSupportManager} will be used, which shows a redbox in dev mode and rethrows * DevSupportManager} will be used, which shows a redbox in dev mode and rethrows (crashes the
* (crashes the app) in prod mode. * app) in prod mode.
*/ */
public ReactInstanceManagerBuilder setNativeModuleCallExceptionHandler( public ReactInstanceManagerBuilder setNativeModuleCallExceptionHandler(
NativeModuleCallExceptionHandler handler) { NativeModuleCallExceptionHandler handler) {
@ -232,8 +219,9 @@ public class ReactInstanceManagerBuilder {
} }
/** /**
* Instantiates a new {@link ReactInstanceManager}. * Instantiates a new {@link ReactInstanceManager}. Before calling {@code build}, the following
* Before calling {@code build}, the following must be called: * must be called:
*
* <ul> * <ul>
* <li>{@link #setApplication} * <li>{@link #setApplication}
* <li>{@link #setCurrentActivity} if the activity has already resumed * <li>{@link #setCurrentActivity} if the activity has already resumed
@ -243,13 +231,11 @@ public class ReactInstanceManagerBuilder {
*/ */
public ReactInstanceManager build() { public ReactInstanceManager build() {
Assertions.assertNotNull( Assertions.assertNotNull(
mApplication, mApplication, "Application property has not been set with this builder");
"Application property has not been set with this builder");
if (mInitialLifecycleState == LifecycleState.RESUMED) { if (mInitialLifecycleState == LifecycleState.RESUMED) {
Assertions.assertNotNull( Assertions.assertNotNull(
mCurrentActivity, mCurrentActivity, "Activity needs to be set if initial lifecycle state is resumed");
"Activity needs to be set if initial lifecycle state is resumed");
} }
Assertions.assertCondition( Assertions.assertCondition(

Просмотреть файл

@ -1,31 +1,28 @@
/** /**
* Copyright (c) Facebook, Inc. and its affiliates. * Copyright (c) Facebook, Inc. and its affiliates.
* *
* This source code is licensed under the MIT license found in the * <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* LICENSE file in the root directory of this source tree. * directory of this source tree.
*/ */
package com.facebook.react; package com.facebook.react;
import java.util.List;
import com.facebook.react.bridge.NativeModule; import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReactApplicationContext;
import java.util.List;
/** /**
* A simple wrapper for ReactPackage to make it aware of its {@link ReactInstanceManager} * A simple wrapper for ReactPackage to make it aware of its {@link ReactInstanceManager} when
* when creating native modules. This is useful when the package needs to ask * creating native modules. This is useful when the package needs to ask the instance manager for
* the instance manager for more information, like {@link DevSupportManager}. * more information, like {@link DevSupportManager}.
* *
* TODO(t11394819): Consolidate this with LazyReactPackage * <p>TODO(t11394819): Consolidate this with LazyReactPackage Use {@link ReactPackage} or {@link
* Use {@link ReactPackage} or {@link LazyReactPackage} and inject reactInstanceManager as a part of when plugins are initialized. * LazyReactPackage} and inject reactInstanceManager as a part of when plugins are initialized.
*/ */
@Deprecated @Deprecated
public abstract class ReactInstancePackage implements ReactPackage { public abstract class ReactInstancePackage implements ReactPackage {
public abstract List<NativeModule> createNativeModules( public abstract List<NativeModule> createNativeModules(
ReactApplicationContext reactContext, ReactApplicationContext reactContext, ReactInstanceManager reactInstanceManager);
ReactInstanceManager reactInstanceManager);
@Override @Override
public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) { public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {

Просмотреть файл

@ -1,10 +1,9 @@
/** /**
* Copyright (c) Facebook, Inc. and its affiliates. * Copyright (c) Facebook, Inc. and its affiliates.
* *
* This source code is licensed under the MIT license found in the * <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* LICENSE file in the root directory of this source tree. * directory of this source tree.
*/ */
package com.facebook.react; package com.facebook.react;
import android.app.Application; import android.app.Application;
@ -32,9 +31,7 @@ public abstract class ReactNativeHost {
mApplication = application; mApplication = application;
} }
/** /** Get the current {@link ReactInstanceManager} instance, or create one. */
* Get the current {@link ReactInstanceManager} instance, or create one.
*/
public ReactInstanceManager getReactInstanceManager() { public ReactInstanceManager getReactInstanceManager() {
if (mReactInstanceManager == null) { if (mReactInstanceManager == null) {
ReactMarker.logMarker(ReactMarkerConstants.GET_REACT_INSTANCE_MANAGER_START); ReactMarker.logMarker(ReactMarkerConstants.GET_REACT_INSTANCE_MANAGER_START);
@ -65,7 +62,8 @@ public abstract class ReactNativeHost {
protected ReactInstanceManager createReactInstanceManager() { protected ReactInstanceManager createReactInstanceManager() {
ReactMarker.logMarker(ReactMarkerConstants.BUILD_REACT_INSTANCE_MANAGER_START); ReactMarker.logMarker(ReactMarkerConstants.BUILD_REACT_INSTANCE_MANAGER_START);
ReactInstanceManagerBuilder builder = ReactInstanceManager.builder() ReactInstanceManagerBuilder builder =
ReactInstanceManager.builder()
.setApplication(mApplication) .setApplication(mApplication)
.setJSMainModulePath(getJSMainModuleName()) .setJSMainModulePath(getJSMainModuleName())
.setUseDeveloperSupport(getUseDeveloperSupport()) .setUseDeveloperSupport(getUseDeveloperSupport())
@ -90,17 +88,12 @@ public abstract class ReactNativeHost {
return reactInstanceManager; return reactInstanceManager;
} }
/** /** Get the {@link RedBoxHandler} to send RedBox-related callbacks to. */
* Get the {@link RedBoxHandler} to send RedBox-related callbacks to.
*/
protected @Nullable RedBoxHandler getRedBoxHandler() { protected @Nullable RedBoxHandler getRedBoxHandler() {
return null; return null;
} }
/** /** Get the {@link JavaScriptExecutorFactory}. Override this to use a custom Executor. */
* Get the {@link JavaScriptExecutorFactory}. Override this to use a custom
* Executor.
*/
protected @Nullable JavaScriptExecutorFactory getJavaScriptExecutorFactory() { protected @Nullable JavaScriptExecutorFactory getJavaScriptExecutorFactory() {
return null; return null;
} }
@ -113,22 +106,20 @@ public abstract class ReactNativeHost {
* Get the {@link UIImplementationProvider} to use. Override this method if you want to use a * Get the {@link UIImplementationProvider} to use. Override this method if you want to use a
* custom UI implementation. * custom UI implementation.
* *
* Note: this is very advanced functionality, in 99% of cases you don't need to override this. * <p>Note: this is very advanced functionality, in 99% of cases you don't need to override this.
*/ */
protected UIImplementationProvider getUIImplementationProvider() { protected UIImplementationProvider getUIImplementationProvider() {
return new UIImplementationProvider(); return new UIImplementationProvider();
} }
protected @Nullable protected @Nullable JSIModulePackage getJSIModulePackage() {
JSIModulePackage getJSIModulePackage() {
return null; return null;
} }
/** /**
* Returns the name of the main module. Determines the URL used to fetch the JS bundle * Returns the name of the main module. Determines the URL used to fetch the JS bundle from the
* from the packager server. It is only used when dev support is enabled. * packager server. It is only used when dev support is enabled. This is the first file to be
* This is the first file to be executed once the {@link ReactInstanceManager} is created. * executed once the {@link ReactInstanceManager} is created. e.g. "index.android"
* e.g. "index.android"
*/ */
protected String getJSMainModuleName() { protected String getJSMainModuleName() {
return "index.android"; return "index.android";
@ -136,9 +127,8 @@ public abstract class ReactNativeHost {
/** /**
* Returns a custom path of the bundle file. This is used in cases the bundle should be loaded * Returns a custom path of the bundle file. This is used in cases the bundle should be loaded
* from a custom path. By default it is loaded from Android assets, from a path specified * from a custom path. By default it is loaded from Android assets, from a path specified by
* by {@link getBundleAssetName}. * {@link getBundleAssetName}. e.g. "file://sdcard/myapp_cache/index.android.bundle"
* e.g. "file://sdcard/myapp_cache/index.android.bundle"
*/ */
protected @Nullable String getJSBundleFile() { protected @Nullable String getJSBundleFile() {
return null; return null;
@ -146,24 +136,20 @@ public abstract class ReactNativeHost {
/** /**
* Returns the name of the bundle in assets. If this is null, and no file path is specified for * Returns the name of the bundle in assets. If this is null, and no file path is specified for
* the bundle, the app will only work with {@code getUseDeveloperSupport} enabled and will * the bundle, the app will only work with {@code getUseDeveloperSupport} enabled and will always
* always try to load the JS bundle from the packager server. * try to load the JS bundle from the packager server. e.g. "index.android.bundle"
* e.g. "index.android.bundle"
*/ */
protected @Nullable String getBundleAssetName() { protected @Nullable String getBundleAssetName() {
return "index.android.bundle"; return "index.android.bundle";
} }
/** /** Returns whether dev mode should be enabled. This enables e.g. the dev menu. */
* Returns whether dev mode should be enabled. This enables e.g. the dev menu.
*/
public abstract boolean getUseDeveloperSupport(); public abstract boolean getUseDeveloperSupport();
/** /**
* Returns a list of {@link ReactPackage} used by the app. * Returns a list of {@link ReactPackage} used by the app. You'll most likely want to return at
* You'll most likely want to return at least the {@code MainReactPackage}. * least the {@code MainReactPackage}. If your app uses additional views or modules besides the
* If your app uses additional views or modules besides the default ones, * default ones, you'll want to include more packages here.
* you'll want to include more packages here.
*/ */
protected abstract List<ReactPackage> getPackages(); protected abstract List<ReactPackage> getPackages();
} }

Просмотреть файл

@ -1,10 +1,9 @@
/** /**
* Copyright (c) Facebook, Inc. and its affiliates. * Copyright (c) Facebook, Inc. and its affiliates.
* *
* This source code is licensed under the MIT license found in the * <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* LICENSE file in the root directory of this source tree. * directory of this source tree.
*/ */
package com.facebook.react; package com.facebook.react;
import com.facebook.react.bridge.NativeModule; import com.facebook.react.bridge.NativeModule;
@ -12,21 +11,18 @@ import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.UIManagerModule; import com.facebook.react.uimanager.UIManagerModule;
import com.facebook.react.uimanager.ViewManager; import com.facebook.react.uimanager.ViewManager;
import java.util.List; import java.util.List;
import javax.annotation.Nonnull; import javax.annotation.Nonnull;
/** /**
* Main interface for providing additional capabilities to the catalyst framework by couple of * Main interface for providing additional capabilities to the catalyst framework by couple of
* different means: * different means: 1) Registering new native modules 2) Registering new JS modules that may be
* 1) Registering new native modules * accessed from native modules or from other parts of the native code (requiring JS modules from
* 2) Registering new JS modules that may be accessed from native modules or from other parts of the * the package doesn't mean it will automatically be included as a part of the JS bundle, so there
* native code (requiring JS modules from the package doesn't mean it will automatically be included * should be a corresponding piece of code on JS side that will require implementation of that JS
* as a part of the JS bundle, so there should be a corresponding piece of code on JS side that will * module so that it gets bundled) 3) Registering custom native views (view managers) and custom
* require implementation of that JS module so that it gets bundled) * event types 4) Registering natively packaged assets/resources (e.g. images) exposed to JS
* 3) Registering custom native views (view managers) and custom event types
* 4) Registering natively packaged assets/resources (e.g. images) exposed to JS
* *
* TODO(6788500, 6788507): Implement support for adding custom views, events and resources * <p>TODO(6788500, 6788507): Implement support for adding custom views, events and resources
*/ */
public interface ReactPackage { public interface ReactPackage {
@ -37,9 +33,7 @@ public interface ReactPackage {
@Nonnull @Nonnull
List<NativeModule> createNativeModules(@Nonnull ReactApplicationContext reactContext); List<NativeModule> createNativeModules(@Nonnull ReactApplicationContext reactContext);
/** /** @return a list of view managers that should be registered with {@link UIManagerModule} */
* @return a list of view managers that should be registered with {@link UIManagerModule}
*/
@Nonnull @Nonnull
List<ViewManager> createViewManagers(@Nonnull ReactApplicationContext reactContext); List<ViewManager> createViewManagers(@Nonnull ReactApplicationContext reactContext);
} }

Просмотреть файл

@ -1,10 +1,9 @@
/** /**
* Copyright (c) Facebook, Inc. and its affiliates. * Copyright (c) Facebook, Inc. and its affiliates.
* *
* This source code is licensed under the MIT license found in the * <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* LICENSE file in the root directory of this source tree. * directory of this source tree.
*/ */
package com.facebook.react; package com.facebook.react;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;

Просмотреть файл

@ -5,11 +5,10 @@
package com.facebook.react; package com.facebook.react;
/** /** Interface for the bridge to call for TTI start and end markers. */
* Interface for the bridge to call for TTI start and end markers.
*/
public interface ReactPackageLogger { public interface ReactPackageLogger {
void startProcessPackage(); void startProcessPackage();
void endProcessPackage(); void endProcessPackage();
} }

Просмотреть файл

@ -1,10 +1,9 @@
/** /**
* Copyright (c) Facebook, Inc. and its affiliates. * Copyright (c) Facebook, Inc. and its affiliates.
* *
* This source code is licensed under the MIT license found in the * <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* LICENSE file in the root directory of this source tree. * directory of this source tree.
*/ */
package com.facebook.react; package com.facebook.react;
import static com.facebook.react.uimanager.common.UIManagerType.DEFAULT; import static com.facebook.react.uimanager.common.UIManagerType.DEFAULT;
@ -46,8 +45,8 @@ import com.facebook.react.uimanager.DisplayMetricsHolder;
import com.facebook.react.uimanager.IllegalViewOperationException; import com.facebook.react.uimanager.IllegalViewOperationException;
import com.facebook.react.uimanager.JSTouchDispatcher; import com.facebook.react.uimanager.JSTouchDispatcher;
import com.facebook.react.uimanager.PixelUtil; import com.facebook.react.uimanager.PixelUtil;
import com.facebook.react.uimanager.RootView;
import com.facebook.react.uimanager.ReactRoot; import com.facebook.react.uimanager.ReactRoot;
import com.facebook.react.uimanager.RootView;
import com.facebook.react.uimanager.UIManagerHelper; import com.facebook.react.uimanager.UIManagerHelper;
import com.facebook.react.uimanager.UIManagerModule; import com.facebook.react.uimanager.UIManagerModule;
import com.facebook.react.uimanager.common.UIManagerType; import com.facebook.react.uimanager.common.UIManagerType;
@ -62,20 +61,16 @@ import javax.annotation.Nullable;
* ViewGroup#onInterceptTouchEvent} method in order to be notified about the events for all of its * ViewGroup#onInterceptTouchEvent} method in order to be notified about the events for all of its
* children and it's also overriding {@link ViewGroup#requestDisallowInterceptTouchEvent} to make * children and it's also overriding {@link ViewGroup#requestDisallowInterceptTouchEvent} to make
* sure that {@link ViewGroup#onInterceptTouchEvent} will get events even when some child view start * sure that {@link ViewGroup#onInterceptTouchEvent} will get events even when some child view start
* intercepting it. In case when no child view is interested in handling some particular touch event, * intercepting it. In case when no child view is interested in handling some particular touch
* this view's {@link View#onTouchEvent} will still return true in order to be notified about all * event, this view's {@link View#onTouchEvent} will still return true in order to be notified about
* subsequent touch events related to that gesture (in case when JS code wants to handle that * all subsequent touch events related to that gesture (in case when JS code wants to handle that
* gesture). * gesture).
*/ */
public class ReactRootView extends FrameLayout implements RootView, ReactRoot { public class ReactRootView extends FrameLayout implements RootView, ReactRoot {
/** /** Listener interface for react root view events */
* Listener interface for react root view events
*/
public interface ReactRootViewEventListener { public interface ReactRootViewEventListener {
/** /** Called when the react context is attached to a ReactRootView. */
* Called when the react context is attached to a ReactRootView.
*/
void onAttachedToReactInstance(ReactRootView rootView); void onAttachedToReactInstance(ReactRootView rootView);
} }
@ -89,7 +84,8 @@ public class ReactRootView extends FrameLayout implements RootView, ReactRoot {
private boolean mIsAttachedToInstance; private boolean mIsAttachedToInstance;
private boolean mShouldLogContentAppeared; private boolean mShouldLogContentAppeared;
private @Nullable JSTouchDispatcher mJSTouchDispatcher; private @Nullable JSTouchDispatcher mJSTouchDispatcher;
private final ReactAndroidHWInputDeviceHelper mAndroidHWInputDeviceHelper = new ReactAndroidHWInputDeviceHelper(this); private final ReactAndroidHWInputDeviceHelper mAndroidHWInputDeviceHelper =
new ReactAndroidHWInputDeviceHelper(this);
private boolean mWasMeasured = false; private boolean mWasMeasured = false;
private int mWidthMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED); private int mWidthMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
private int mHeightMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED); private int mHeightMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
@ -135,8 +131,8 @@ public class ReactRootView extends FrameLayout implements RootView, ReactRoot {
Systrace.beginSection(TRACE_TAG_REACT_JAVA_BRIDGE, "ReactRootView.onMeasure"); Systrace.beginSection(TRACE_TAG_REACT_JAVA_BRIDGE, "ReactRootView.onMeasure");
try { try {
boolean measureSpecsUpdated = widthMeasureSpec != mWidthMeasureSpec || boolean measureSpecsUpdated =
heightMeasureSpec != mHeightMeasureSpec; widthMeasureSpec != mWidthMeasureSpec || heightMeasureSpec != mHeightMeasureSpec;
mWidthMeasureSpec = widthMeasureSpec; mWidthMeasureSpec = widthMeasureSpec;
mHeightMeasureSpec = heightMeasureSpec; mHeightMeasureSpec = heightMeasureSpec;
@ -189,8 +185,9 @@ public class ReactRootView extends FrameLayout implements RootView, ReactRoot {
@Override @Override
public void onChildStartedNativeGesture(MotionEvent androidEvent) { public void onChildStartedNativeGesture(MotionEvent androidEvent) {
if (mReactInstanceManager == null || !mIsAttachedToInstance || if (mReactInstanceManager == null
mReactInstanceManager.getCurrentReactContext() == null) { || !mIsAttachedToInstance
|| mReactInstanceManager.getCurrentReactContext() == null) {
FLog.w( FLog.w(
ReactConstants.TAG, ReactConstants.TAG,
"Unable to dispatch touch to JS as the catalyst instance has not been attached"); "Unable to dispatch touch to JS as the catalyst instance has not been attached");
@ -198,12 +195,12 @@ public class ReactRootView extends FrameLayout implements RootView, ReactRoot {
} }
if (mJSTouchDispatcher == null) { if (mJSTouchDispatcher == null) {
FLog.w( FLog.w(
ReactConstants.TAG, ReactConstants.TAG, "Unable to dispatch touch to JS before the dispatcher is available");
"Unable to dispatch touch to JS before the dispatcher is available");
return; return;
} }
ReactContext reactContext = mReactInstanceManager.getCurrentReactContext(); ReactContext reactContext = mReactInstanceManager.getCurrentReactContext();
EventDispatcher eventDispatcher = reactContext.getNativeModule(UIManagerModule.class).getEventDispatcher(); EventDispatcher eventDispatcher =
reactContext.getNativeModule(UIManagerModule.class).getEventDispatcher();
mJSTouchDispatcher.onChildStartedNativeGesture(androidEvent, eventDispatcher); mJSTouchDispatcher.onChildStartedNativeGesture(androidEvent, eventDispatcher);
} }
@ -235,8 +232,9 @@ public class ReactRootView extends FrameLayout implements RootView, ReactRoot {
@Override @Override
public boolean dispatchKeyEvent(KeyEvent ev) { public boolean dispatchKeyEvent(KeyEvent ev) {
if (mReactInstanceManager == null || !mIsAttachedToInstance || if (mReactInstanceManager == null
mReactInstanceManager.getCurrentReactContext() == null) { || !mIsAttachedToInstance
|| mReactInstanceManager.getCurrentReactContext() == null) {
FLog.w( FLog.w(
ReactConstants.TAG, ReactConstants.TAG,
"Unable to handle key event as the catalyst instance has not been attached"); "Unable to handle key event as the catalyst instance has not been attached");
@ -248,8 +246,9 @@ public class ReactRootView extends FrameLayout implements RootView, ReactRoot {
@Override @Override
protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) { protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) {
if (mReactInstanceManager == null || !mIsAttachedToInstance || if (mReactInstanceManager == null
mReactInstanceManager.getCurrentReactContext() == null) { || !mIsAttachedToInstance
|| mReactInstanceManager.getCurrentReactContext() == null) {
FLog.w( FLog.w(
ReactConstants.TAG, ReactConstants.TAG,
"Unable to handle focus changed event as the catalyst instance has not been attached"); "Unable to handle focus changed event as the catalyst instance has not been attached");
@ -262,8 +261,9 @@ public class ReactRootView extends FrameLayout implements RootView, ReactRoot {
@Override @Override
public void requestChildFocus(View child, View focused) { public void requestChildFocus(View child, View focused) {
if (mReactInstanceManager == null || !mIsAttachedToInstance || if (mReactInstanceManager == null
mReactInstanceManager.getCurrentReactContext() == null) { || !mIsAttachedToInstance
|| mReactInstanceManager.getCurrentReactContext() == null) {
FLog.w( FLog.w(
ReactConstants.TAG, ReactConstants.TAG,
"Unable to handle child focus changed event as the catalyst instance has not been attached"); "Unable to handle child focus changed event as the catalyst instance has not been attached");
@ -275,8 +275,9 @@ public class ReactRootView extends FrameLayout implements RootView, ReactRoot {
} }
private void dispatchJSTouchEvent(MotionEvent event) { private void dispatchJSTouchEvent(MotionEvent event) {
if (mReactInstanceManager == null || !mIsAttachedToInstance || if (mReactInstanceManager == null
mReactInstanceManager.getCurrentReactContext() == null) { || !mIsAttachedToInstance
|| mReactInstanceManager.getCurrentReactContext() == null) {
FLog.w( FLog.w(
ReactConstants.TAG, ReactConstants.TAG,
"Unable to dispatch touch to JS as the catalyst instance has not been attached"); "Unable to dispatch touch to JS as the catalyst instance has not been attached");
@ -284,12 +285,12 @@ public class ReactRootView extends FrameLayout implements RootView, ReactRoot {
} }
if (mJSTouchDispatcher == null) { if (mJSTouchDispatcher == null) {
FLog.w( FLog.w(
ReactConstants.TAG, ReactConstants.TAG, "Unable to dispatch touch to JS before the dispatcher is available");
"Unable to dispatch touch to JS before the dispatcher is available");
return; return;
} }
ReactContext reactContext = mReactInstanceManager.getCurrentReactContext(); ReactContext reactContext = mReactInstanceManager.getCurrentReactContext();
EventDispatcher eventDispatcher = reactContext.getNativeModule(UIManagerModule.class).getEventDispatcher(); EventDispatcher eventDispatcher =
reactContext.getNativeModule(UIManagerModule.class).getEventDispatcher();
mJSTouchDispatcher.handleTouchEvent(event, eventDispatcher); mJSTouchDispatcher.handleTouchEvent(event, eventDispatcher);
} }
@ -349,24 +350,23 @@ public class ReactRootView extends FrameLayout implements RootView, ReactRoot {
return this; return this;
} }
/** /** {@see #startReactApplication(ReactInstanceManager, String, android.os.Bundle)} */
* {@see #startReactApplication(ReactInstanceManager, String, android.os.Bundle)}
*/
public void startReactApplication(ReactInstanceManager reactInstanceManager, String moduleName) { public void startReactApplication(ReactInstanceManager reactInstanceManager, String moduleName) {
startReactApplication(reactInstanceManager, moduleName, null); startReactApplication(reactInstanceManager, moduleName, null);
} }
/** /** {@see #startReactApplication(ReactInstanceManager, String, android.os.Bundle, String)} */
* {@see #startReactApplication(ReactInstanceManager, String, android.os.Bundle, String)} public void startReactApplication(
*/ ReactInstanceManager reactInstanceManager,
public void startReactApplication(ReactInstanceManager reactInstanceManager, String moduleName, @Nullable Bundle initialProperties) { String moduleName,
@Nullable Bundle initialProperties) {
startReactApplication(reactInstanceManager, moduleName, initialProperties, null); startReactApplication(reactInstanceManager, moduleName, initialProperties, null);
} }
/** /**
* Schedule rendering of the react component rendered by the JS application from the given JS * Schedule rendering of the react component rendered by the JS application from the given JS
* module (@{param moduleName}) using provided {@param reactInstanceManager} to attach to the * module (@{param moduleName}) using provided {@param reactInstanceManager} to attach to the JS
* JS context of that manager. Extra parameter {@param launchOptions} can be used to pass initial * context of that manager. Extra parameter {@param launchOptions} can be used to pass initial
* properties for the react component. * properties for the react component.
*/ */
public void startReactApplication( public void startReactApplication(
@ -498,8 +498,8 @@ public class ReactRootView extends FrameLayout implements RootView, ReactRoot {
} }
/** /**
* Calls into JS to start the React application. Can be called multiple times with the * Calls into JS to start the React application. Can be called multiple times with the same
* same rootTag, which will re-render the application from the root. * rootTag, which will re-render the application from the root.
*/ */
@Override @Override
public void runApplication() { public void runApplication() {
@ -541,8 +541,8 @@ public class ReactRootView extends FrameLayout implements RootView, ReactRoot {
} }
/** /**
* Is used by unit test to setup mIsAttachedToWindow flags, that will let this * Is used by unit test to setup mIsAttachedToWindow flags, that will let this view to be properly
* view to be properly attached to catalyst instance by startReactApplication call * attached to catalyst instance by startReactApplication call
*/ */
@VisibleForTesting @VisibleForTesting
/* package */ void simulateAttachForTesting() { /* package */ void simulateAttachForTesting() {
@ -577,11 +577,11 @@ public class ReactRootView extends FrameLayout implements RootView, ReactRoot {
super.finalize(); super.finalize();
Assertions.assertCondition( Assertions.assertCondition(
!mIsAttachedToInstance, !mIsAttachedToInstance,
"The application this ReactRootView was rendering was not unmounted before the " + "The application this ReactRootView was rendering was not unmounted before the "
"ReactRootView was garbage collected. This usually means that your application is " + + "ReactRootView was garbage collected. This usually means that your application is "
"leaking large amounts of memory. To solve this, make sure to call " + + "leaking large amounts of memory. To solve this, make sure to call "
"ReactRootView#unmountReactApplication in the onDestroy() of your hosting Activity or in " + + "ReactRootView#unmountReactApplication in the onDestroy() of your hosting Activity or in "
"the onDestroyView() of your hosting Fragment."); + "the onDestroyView() of your hosting Fragment.");
} }
public int getRootViewTag() { public int getRootViewTag() {
@ -594,8 +594,7 @@ public class ReactRootView extends FrameLayout implements RootView, ReactRoot {
@Override @Override
public void handleException(final Throwable t) { public void handleException(final Throwable t) {
if (mReactInstanceManager == null if (mReactInstanceManager == null || mReactInstanceManager.getCurrentReactContext() == null) {
|| mReactInstanceManager.getCurrentReactContext() == null) {
throw new RuntimeException(t); throw new RuntimeException(t);
} }
@ -619,7 +618,8 @@ public class ReactRootView extends FrameLayout implements RootView, ReactRoot {
/* package */ void sendEvent(String eventName, @Nullable WritableMap params) { /* package */ void sendEvent(String eventName, @Nullable WritableMap params) {
if (mReactInstanceManager != null) { if (mReactInstanceManager != null) {
mReactInstanceManager.getCurrentReactContext() mReactInstanceManager
.getCurrentReactContext()
.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class) .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
.emit(eventName, params); .emit(eventName, params);
} }
@ -642,8 +642,9 @@ public class ReactRootView extends FrameLayout implements RootView, ReactRoot {
@Override @Override
public void onGlobalLayout() { public void onGlobalLayout() {
if (mReactInstanceManager == null || !mIsAttachedToInstance || if (mReactInstanceManager == null
mReactInstanceManager.getCurrentReactContext() == null) { || !mIsAttachedToInstance
|| mReactInstanceManager.getCurrentReactContext() == null) {
return; return;
} }
checkForKeyboardEvents(); checkForKeyboardEvents();
@ -660,35 +661,34 @@ public class ReactRootView extends FrameLayout implements RootView, ReactRoot {
mKeyboardHeight != heightDiff && heightDiff > mMinKeyboardHeightDetected; mKeyboardHeight != heightDiff && heightDiff > mMinKeyboardHeightDetected;
if (isKeyboardShowingOrKeyboardHeightChanged) { if (isKeyboardShowingOrKeyboardHeightChanged) {
mKeyboardHeight = heightDiff; mKeyboardHeight = heightDiff;
sendEvent("keyboardDidShow", sendEvent(
"keyboardDidShow",
createKeyboardEventPayload( createKeyboardEventPayload(
PixelUtil.toDIPFromPixel(mVisibleViewArea.bottom), PixelUtil.toDIPFromPixel(mVisibleViewArea.bottom),
PixelUtil.toDIPFromPixel(mVisibleViewArea.left), PixelUtil.toDIPFromPixel(mVisibleViewArea.left),
PixelUtil.toDIPFromPixel(mVisibleViewArea.width()), PixelUtil.toDIPFromPixel(mVisibleViewArea.width()),
PixelUtil.toDIPFromPixel(mKeyboardHeight)) PixelUtil.toDIPFromPixel(mKeyboardHeight)));
);
return; return;
} }
boolean isKeyboardHidden = boolean isKeyboardHidden = mKeyboardHeight != 0 && heightDiff <= mMinKeyboardHeightDetected;
mKeyboardHeight != 0 && heightDiff <= mMinKeyboardHeightDetected;
if (isKeyboardHidden) { if (isKeyboardHidden) {
mKeyboardHeight = 0; mKeyboardHeight = 0;
sendEvent("keyboardDidHide", sendEvent(
"keyboardDidHide",
createKeyboardEventPayload( createKeyboardEventPayload(
PixelUtil.toDIPFromPixel(mVisibleViewArea.height()), PixelUtil.toDIPFromPixel(mVisibleViewArea.height()),
0, 0,
PixelUtil.toDIPFromPixel(mVisibleViewArea.width()), PixelUtil.toDIPFromPixel(mVisibleViewArea.width()),
0 0));
)
);
} }
} }
private void checkForDeviceOrientationChanges() { private void checkForDeviceOrientationChanges() {
final int rotation = final int rotation =
((WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE)) ((WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE))
.getDefaultDisplay().getRotation(); .getDefaultDisplay()
.getRotation();
if (mDeviceRotation == rotation) { if (mDeviceRotation == rotation) {
return; return;
} }
@ -699,9 +699,10 @@ public class ReactRootView extends FrameLayout implements RootView, ReactRoot {
private void checkForDeviceDimensionsChanges() { private void checkForDeviceDimensionsChanges() {
// Get current display metrics. // Get current display metrics.
DisplayMetricsHolder.initDisplayMetrics(getContext()); DisplayMetricsHolder.initDisplayMetrics(getContext());
// Check changes to both window and screen display metrics since they may not update at the same time. // Check changes to both window and screen display metrics since they may not update at the
if (!areMetricsEqual(mWindowMetrics, DisplayMetricsHolder.getWindowDisplayMetrics()) || // same time.
!areMetricsEqual(mScreenMetrics, DisplayMetricsHolder.getScreenDisplayMetrics())) { if (!areMetricsEqual(mWindowMetrics, DisplayMetricsHolder.getWindowDisplayMetrics())
|| !areMetricsEqual(mScreenMetrics, DisplayMetricsHolder.getScreenDisplayMetrics())) {
mWindowMetrics.setTo(DisplayMetricsHolder.getWindowDisplayMetrics()); mWindowMetrics.setTo(DisplayMetricsHolder.getWindowDisplayMetrics());
mScreenMetrics.setTo(DisplayMetricsHolder.getScreenDisplayMetrics()); mScreenMetrics.setTo(DisplayMetricsHolder.getScreenDisplayMetrics());
emitUpdateDimensionsEvent(); emitUpdateDimensionsEvent();
@ -714,13 +715,13 @@ public class ReactRootView extends FrameLayout implements RootView, ReactRoot {
} else { } else {
// DisplayMetrics didn't have an equals method before API 17. // DisplayMetrics didn't have an equals method before API 17.
// Check all public fields manually. // Check all public fields manually.
return displayMetrics.widthPixels == otherMetrics.widthPixels && return displayMetrics.widthPixels == otherMetrics.widthPixels
displayMetrics.heightPixels == otherMetrics.heightPixels && && displayMetrics.heightPixels == otherMetrics.heightPixels
displayMetrics.density == otherMetrics.density && && displayMetrics.density == otherMetrics.density
displayMetrics.densityDpi == otherMetrics.densityDpi && && displayMetrics.densityDpi == otherMetrics.densityDpi
displayMetrics.scaledDensity == otherMetrics.scaledDensity && && displayMetrics.scaledDensity == otherMetrics.scaledDensity
displayMetrics.xdpi == otherMetrics.xdpi && && displayMetrics.xdpi == otherMetrics.xdpi
displayMetrics.ydpi == otherMetrics.ydpi; && displayMetrics.ydpi == otherMetrics.ydpi;
} }
} }
@ -766,7 +767,8 @@ public class ReactRootView extends FrameLayout implements RootView, ReactRoot {
.emitUpdateDimensionsEvent(); .emitUpdateDimensionsEvent();
} }
private WritableMap createKeyboardEventPayload(double screenY, double screenX, double width, double height) { private WritableMap createKeyboardEventPayload(
double screenY, double screenX, double width, double height) {
WritableMap keyboardEventParams = Arguments.createMap(); WritableMap keyboardEventParams = Arguments.createMap();
WritableMap endCoordinates = Arguments.createMap(); WritableMap endCoordinates = Arguments.createMap();

Просмотреть файл

@ -1,10 +1,9 @@
/** /**
* Copyright (c) Facebook, Inc. and its affiliates. * Copyright (c) Facebook, Inc. and its affiliates.
* *
* This source code is licensed under the MIT license found in the * <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* LICENSE file in the root directory of this source tree. * directory of this source tree.
*/ */
package com.facebook.react; package com.facebook.react;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;

Просмотреть файл

@ -1,10 +1,9 @@
/** /**
* Copyright (c) Facebook, Inc. and its affiliates. * Copyright (c) Facebook, Inc. and its affiliates.
* *
* This source code is licensed under the MIT license found in the * <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* LICENSE file in the root directory of this source tree. * directory of this source tree.
*/ */
package com.facebook.react; package com.facebook.react;
import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReactApplicationContext;
@ -17,7 +16,8 @@ public interface ViewManagerOnDemandReactPackage {
* Provides a list of names of ViewManagers with which these modules can be accessed from JS. * Provides a list of names of ViewManagers with which these modules can be accessed from JS.
* Typically, this is ViewManager.getName(). * Typically, this is ViewManager.getName().
*/ */
@Nullable List<String> getViewManagerNames(ReactApplicationContext reactContext); @Nullable
List<String> getViewManagerNames(ReactApplicationContext reactContext);
/** /**
* Creates and returns a ViewManager with a specific name {@param viewManagerName}. It's up to an * Creates and returns a ViewManager with a specific name {@param viewManagerName}. It's up to an
* implementing package how to interpret the name. * implementing package how to interpret the name.

Просмотреть файл

@ -1,10 +1,9 @@
/** /**
* Copyright (c) Facebook, Inc. and its affiliates. * Copyright (c) Facebook, Inc. and its affiliates.
* *
* This source code is licensed under the MIT license found in the * <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* LICENSE file in the root directory of this source tree. * directory of this source tree.
*/ */
package com.facebook.react.animated; package com.facebook.react.animated;
import com.facebook.react.bridge.JSApplicationCausedNativeException; import com.facebook.react.bridge.JSApplicationCausedNativeException;
@ -21,8 +20,7 @@ import com.facebook.react.bridge.ReadableMap;
private final int[] mInputNodes; private final int[] mInputNodes;
public AdditionAnimatedNode( public AdditionAnimatedNode(
ReadableMap config, ReadableMap config, NativeAnimatedNodesManager nativeAnimatedNodesManager) {
NativeAnimatedNodesManager nativeAnimatedNodesManager) {
mNativeAnimatedNodesManager = nativeAnimatedNodesManager; mNativeAnimatedNodesManager = nativeAnimatedNodesManager;
ReadableArray inputNodes = config.getArray("input"); ReadableArray inputNodes = config.getArray("input");
mInputNodes = new int[inputNodes.size()]; mInputNodes = new int[inputNodes.size()];
@ -39,8 +37,8 @@ import com.facebook.react.bridge.ReadableMap;
if (animatedNode != null && animatedNode instanceof ValueAnimatedNode) { if (animatedNode != null && animatedNode instanceof ValueAnimatedNode) {
mValue += ((ValueAnimatedNode) animatedNode).getValue(); mValue += ((ValueAnimatedNode) animatedNode).getValue();
} else { } else {
throw new JSApplicationCausedNativeException("Illegal node ID set as an input for " + throw new JSApplicationCausedNativeException(
"Animated.Add node"); "Illegal node ID set as an input for " + "Animated.Add node");
} }
} }
} }

Просмотреть файл

@ -1,22 +1,17 @@
/** /**
* Copyright (c) Facebook, Inc. and its affiliates. * Copyright (c) Facebook, Inc. and its affiliates.
* *
* This source code is licensed under the MIT license found in the * <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* LICENSE file in the root directory of this source tree. * directory of this source tree.
*/ */
package com.facebook.react.animated; package com.facebook.react.animated;
import com.facebook.infer.annotation.Assertions; import com.facebook.infer.annotation.Assertions;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import javax.annotation.Nullable; import javax.annotation.Nullable;
/** /** Base class for all Animated.js library node types that can be created on the "native" side. */
* Base class for all Animated.js library node types that can be created on the "native" side.
*/
/*package*/ abstract class AnimatedNode { /*package*/ abstract class AnimatedNode {
public static final int INITIAL_BFS_COLOR = 0; public static final int INITIAL_BFS_COLOR = 0;
@ -46,24 +41,19 @@ import javax.annotation.Nullable;
/** /**
* Subclasses may want to override this method in order to store a reference to the parent of a * Subclasses may want to override this method in order to store a reference to the parent of a
* given node that can then be used to calculate current node's value in {@link #update}. * given node that can then be used to calculate current node's value in {@link #update}. In that
* In that case it is important to also override {@link #onDetachedFromNode} to clear that * case it is important to also override {@link #onDetachedFromNode} to clear that reference once
* reference once current node gets detached. * current node gets detached.
*/ */
public void onAttachedToNode(AnimatedNode parent) { public void onAttachedToNode(AnimatedNode parent) {}
}
/** /** See {@link #onAttachedToNode} */
* See {@link #onAttachedToNode} public void onDetachedFromNode(AnimatedNode parent) {}
*/
public void onDetachedFromNode(AnimatedNode parent) {
}
/** /**
* This method will be run on each node at most once every repetition of the animation loop. It * This method will be run on each node at most once every repetition of the animation loop. It
* will be executed on a node only when all the node's parent has already been updated. Therefore * will be executed on a node only when all the node's parent has already been updated. Therefore
* it can be used to calculate node's value. * it can be used to calculate node's value.
*/ */
public void update() { public void update() {}
}
} }

Просмотреть файл

@ -1,15 +1,12 @@
/** /**
* Copyright (c) Facebook, Inc. and its affiliates. * Copyright (c) Facebook, Inc. and its affiliates.
* *
* This source code is licensed under the MIT license found in the * <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* LICENSE file in the root directory of this source tree. * directory of this source tree.
*/ */
package com.facebook.react.animated; package com.facebook.react.animated;
/** /** Interface used to listen to {@link ValueAnimatedNode} updates. */
* Interface used to listen to {@link ValueAnimatedNode} updates.
*/
public interface AnimatedNodeValueListener { public interface AnimatedNodeValueListener {
void onValueUpdate(double value); void onValueUpdate(double value);
} }

Просмотреть файл

@ -1,10 +1,9 @@
/** /**
* Copyright (c) Facebook, Inc. and its affiliates. * Copyright (c) Facebook, Inc. and its affiliates.
* *
* This source code is licensed under the MIT license found in the * <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* LICENSE file in the root directory of this source tree. * directory of this source tree.
*/ */
package com.facebook.react.animated; package com.facebook.react.animated;
import com.facebook.react.bridge.Callback; import com.facebook.react.bridge.Callback;

Просмотреть файл

@ -1,10 +1,9 @@
/** /**
* Copyright (c) Facebook, Inc. and its affiliates. * Copyright (c) Facebook, Inc. and its affiliates.
* *
* This source code is licensed under the MIT license found in the * <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* LICENSE file in the root directory of this source tree. * directory of this source tree.
*/ */
package com.facebook.react.animated; package com.facebook.react.animated;
import com.facebook.react.bridge.ReadableMap; import com.facebook.react.bridge.ReadableMap;
@ -54,9 +53,10 @@ public class DecayAnimation extends AnimationDriver {
mLastValue = mAnimatedValue.mValue; mLastValue = mAnimatedValue.mValue;
} }
final double value = mFromValue + final double value =
(mVelocity / (1 - mDeceleration)) * mFromValue
(1 - Math.exp(-(1 - mDeceleration) * (frameTimeMillis - mStartFrameTimeMillis))); + (mVelocity / (1 - mDeceleration))
* (1 - Math.exp(-(1 - mDeceleration) * (frameTimeMillis - mStartFrameTimeMillis)));
if (Math.abs(mLastValue - value) < 0.1) { if (Math.abs(mLastValue - value) < 0.1) {

Некоторые файлы не были показаны из-за слишком большого количества измененных файлов Показать больше