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.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* directory of this source tree.
*/
package com.facebook.react.uiapp;
import android.os.Bundle;
import com.facebook.react.ReactActivity;
import com.facebook.react.ReactActivityDelegate;
import javax.annotation.Nullable;
public class RNTesterActivity extends ReactActivity {
@ -31,7 +27,8 @@ public class RNTesterActivity extends ReactActivity {
// Get remote param before calling super which uses it
Bundle bundle = mActivity.getIntent().getExtras();
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("Example")
.toString();

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

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

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

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

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

@ -1,23 +1,19 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
* <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* directory of this source tree.
*/
package com.facebook.react.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.assertTrue;
/**
* NativeModule for tests that allows assertions from JS to propagate to Java.
*/
import com.facebook.react.bridge.BaseJavaModule;
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 {
private boolean mGotSuccess;

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

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

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

@ -1,22 +1,18 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
* <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* directory of this source tree.
*/
package com.facebook.react.testing;
import javax.annotation.Nullable;
import com.facebook.react.bridge.BaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.ReadableArray;
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 {
@Override
@ -34,18 +30,14 @@ public final class FakeWebSocketModule extends BaseJavaModule {
final String url,
@Nullable final ReadableArray protocols,
@Nullable final ReadableMap headers,
final int id) {
}
final int id) {}
@ReactMethod
public void close(int code, String reason, int id) {
}
public void close(int code, String reason, int id) {}
@ReactMethod
public void send(String message, int id) {
}
public void send(String message, int id) {}
@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.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
* <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* directory of this source tree.
*/
package com.facebook.react.testing;
import java.util.List;
import android.view.View;
import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.JavaScriptModule;
import com.facebook.react.uimanager.ViewManager;
import com.facebook.react.ReactPackage;
import java.util.List;
/**
* This class wraps {@class ReactInstanceSpecForTest} in {@class ReactPackage} interface.

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

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

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

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

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

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

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

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

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

@ -11,15 +11,14 @@ import static com.facebook.react.bridge.UiThreadUtil.runOnUiThread;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import androidx.fragment.app.FragmentActivity;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.FrameLayout;
import androidx.fragment.app.FragmentActivity;
import com.facebook.infer.annotation.Assertions;
import com.facebook.react.ReactInstanceManager;
import com.facebook.react.ReactInstanceManagerBuilder;
import com.facebook.react.ReactRootView;
import com.facebook.react.bridge.JSIModule;
import com.facebook.react.bridge.JSIModulePackage;
import com.facebook.react.bridge.JSIModuleProvider;
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.testing.idledetection.ReactBridgeIdleSignaler;
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.events.EventDispatcher;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import javax.annotation.Nullable;
public class ReactAppTestActivity extends FragmentActivity
implements DefaultHardwareBackBtnHandler, PermissionAwareActivity {
@ -194,10 +189,12 @@ public class ReactAppTestActivity extends FragmentActivity
waitForBridgeAndUIIdle();
waitForLayout(5000);
} 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();
@ -215,11 +212,11 @@ public class ReactAppTestActivity extends FragmentActivity
builder.addPackage(new MainReactPackage());
}
/**
* The {@link ReactContext#mCurrentActivity} never to be set if initial lifecycle state is resumed.
* So we should call {@link ReactInstanceManagerBuilder#setCurrentActivity}.
* The {@link ReactContext#mCurrentActivity} never to be set if initial lifecycle state is
* resumed. So we should call {@link ReactInstanceManagerBuilder#setCurrentActivity}.
*
* Finally,{@link ReactInstanceManagerBuilder#build()} will create instance of {@link ReactInstanceManager}.
* And also will set {@link ReactContext#mCurrentActivity}.
* <p>Finally,{@link ReactInstanceManagerBuilder#build()} will create instance of {@link
* ReactInstanceManager}. And also will set {@link ReactContext#mCurrentActivity}.
*/
builder.setCurrentActivity(this);
builder
@ -251,10 +248,14 @@ public class ReactAppTestActivity extends FragmentActivity
public UIManager get() {
ViewManagerRegistry viewManagerRegistry =
new ViewManagerRegistry(
mReactInstanceManager.getOrCreateViewManagers(reactApplicationContext));
mReactInstanceManager.getOrCreateViewManagers(
reactApplicationContext));
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;
}
public ReactInstanceSpecForTest setFabricUIManagerFactory(@Nullable FabricUIManagerFactory fabricUIManagerFactory) {
public ReactInstanceSpecForTest setFabricUIManagerFactory(
@Nullable FabricUIManagerFactory fabricUIManagerFactory) {
mFabricUIManagerFactory = fabricUIManagerFactory;
return this;
}

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

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

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

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

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

@ -1,10 +1,9 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
* <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* directory of this source tree.
*/
package com.facebook.react.testing;
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.
*
* Any app-specific code that should run before secondary dex files are loaded
* (like setting up crash reporting) should go in onBaseContextAttached.
* Anything that should run after secondary dex should go in CatalystApplicationImpl.onCreate.
* <p>Any app-specific code that should run before secondary dex files are loaded (like setting up
* crash reporting) should go in onBaseContextAttached. Anything that should run after secondary dex
* should go in CatalystApplicationImpl.onCreate.
*/
public class ReactTestAppShell extends ExopackageApplication<ApplicationLike> {

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

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

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

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

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

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

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

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

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

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

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

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

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

@ -1,15 +1,12 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
* <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* directory of this source tree.
*/
package com.facebook.react.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 {
void waitForBridgeAndUIIdle();

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

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

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

@ -1,10 +1,9 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
* <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* directory of this source tree.
*/
package com.facebook.react.testing.idledetection;
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 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).
* <p/>
* Also waits for any Choreographer callbacks to run after the initial sync since things like UI
* events are initiated from Choreographer callbacks.
*
* <p>Also waits for any Choreographer callbacks to run after the initial sync since things like
* UI events are initiated from Choreographer callbacks.
*/
public static void waitForBridgeAndUIIdle(
ReactBridgeIdleSignaler idleSignaler,
final ReactContext reactContext,
long timeoutMs) {
ReactBridgeIdleSignaler idleSignaler, final ReactContext reactContext, long timeoutMs) {
return;
// TODO: re-enable after cleanup of android-x migration

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

@ -1,14 +1,11 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
* <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* directory of this source tree.
*/
package com.facebook.react.testing.network;
import javax.annotation.Nullable;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.Callback;
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.module.annotations.ReactModule;
import com.facebook.react.modules.core.DeviceEventManagerModule;
import javax.annotation.Nullable;
/**
* 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(
Callback callback,
int status,
@Nullable String headers,
@Nullable String body) {
Callback callback, int status, @Nullable String headers, @Nullable String body) {
callback.invoke(status, headers, body);
}

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

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

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

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

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

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

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

@ -1,19 +1,16 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
* <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* directory of this source tree.
*/
package com.facebook.react.tests;
import java.util.List;
import android.view.MotionEvent;
import com.facebook.react.testing.ReactInstanceSpecForTest;
import com.facebook.react.testing.ReactAppInstrumentationTestCase;
import com.facebook.react.testing.ReactInstanceSpecForTest;
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
@ -30,8 +27,7 @@ public class CatalystMultitouchHandlingTestCase extends ReactAppInstrumentationT
@Override
protected ReactInstanceSpecForTest createReactInstanceSpecForTest() {
return new ReactInstanceSpecForTest()
.addNativeModule(mRecordingModule);
return new ReactInstanceSpecForTest().addNativeModule(mRecordingModule);
}
/**
@ -102,12 +98,27 @@ public class CatalystMultitouchHandlingTestCase extends ReactAppInstrumentationT
final int pointerCount,
final MotionEvent.PointerProperties[] pointerProps,
final MotionEvent.PointerCoords[] pointerCoords) {
getRootView().post(
getRootView()
.post(
new Runnable() {
@Override
public void run() {
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);
event.recycle();
}
@ -117,11 +128,10 @@ public class CatalystMultitouchHandlingTestCase extends ReactAppInstrumentationT
/**
* This method "replay" multi-touch gesture recorded with modified TouchesHelper class that
* generated this piece of code (see https://phabricator.fb.com/P19756940).
* This is not intended to be copied/reused and once we need to have more multitouch gestures
* in instrumentation tests we should either:
* - implement nice generator similar to {@link SingleTouchGestureGenerator}
* - implement gesture recorded that will record touch data using arbitrary format and then read
* generated this piece of code (see https://phabricator.fb.com/P19756940). This is not intended
* to be copied/reused and once we need to have more multitouch gestures in instrumentation tests
* we should either: - implement nice generator similar to {@link SingleTouchGestureGenerator} -
* 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
*/
private void generateRecordedPinchTouchEvents() {
@ -149,7 +159,13 @@ public class CatalystMultitouchHandlingTestCase extends ReactAppInstrumentationT
pointerCoords[0] = createPointerCoords(267.0f, 346.0f);
pointerProps[1] = createPointerProps(1, 1);
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);
pointerProps[1] = createPointerProps(1, 1);
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
}
}

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

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

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

@ -1,10 +1,9 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
* <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* directory of this source tree.
*/
package com.facebook.react.tests;
import com.facebook.react.bridge.CatalystInstance;
@ -28,9 +27,7 @@ import java.util.Arrays;
import java.util.List;
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.")
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 receiveArrayWithBasicTypes(WritableArray array);
void receiveNestedArray(WritableArray nestedArray);
void receiveArrayWithMaps(WritableArray arrayWithMaps);
void receiveMapWithBasicTypes(WritableMap map);
void receiveNestedMap(WritableMap nestedMap);
void receiveMapWithArrays(WritableMap mapWithArrays);
void receiveMapAndArrayWithNullValues(
WritableMap map,
WritableArray array);
void receiveMapAndArrayWithNullValues(WritableMap map, WritableArray array);
void receiveMapWithMultibyteUTF8CharacterString(WritableMap map);
void receiveArrayWithMultibyteUTF8CharacterString(WritableArray array);
}
@ -58,10 +60,8 @@ public class CatalystNativeJavaToJSArgumentsTestCase extends ReactIntegrationTes
protected void setUp() throws Exception {
super.setUp();
List<ViewManager> viewManagers = Arrays.<ViewManager>asList(
new ReactViewManager());
final UIManagerModule mUIManager =
new UIManagerModule(getContext(), viewManagers, 0);
List<ViewManager> viewManagers = Arrays.<ViewManager>asList(new ReactViewManager());
final UIManagerModule mUIManager = new UIManagerModule(getContext(), viewManagers, 0);
UiThreadUtil.runOnUiThread(
new Runnable() {
@Override
@ -73,7 +73,8 @@ public class CatalystNativeJavaToJSArgumentsTestCase extends ReactIntegrationTes
mAssertModule = new AssertModule();
mInstance = ReactTestHelper.catalystInstanceBuilder(this)
mInstance =
ReactTestHelper.catalystInstanceBuilder(this)
.addNativeModule(mAssertModule)
.addNativeModule(new DeviceInfoModule(getContext()))
.addNativeModule(new AppStateModule(getContext()))
@ -83,7 +84,8 @@ public class CatalystNativeJavaToJSArgumentsTestCase extends ReactIntegrationTes
}
public void testBasicTypes() {
mInstance.getJSModule(TestJavaToJSArgumentsModule.class)
mInstance
.getJSModule(TestJavaToJSArgumentsModule.class)
.receiveBasicTypes("foo", 3.14, true, null);
waitForBridgeAndUIIdle();
mAssertModule.verifyAssertsAndReset();
@ -182,7 +184,8 @@ public class CatalystNativeJavaToJSArgumentsTestCase extends ReactIntegrationTes
array.pushArray(null);
array.pushMap(null);
mInstance.getJSModule(TestJavaToJSArgumentsModule.class)
mInstance
.getJSModule(TestJavaToJSArgumentsModule.class)
.receiveMapAndArrayWithNullValues(map, array);
waitForBridgeAndUIIdle();
mAssertModule.verifyAssertsAndReset();

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

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

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

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

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

@ -1,51 +1,35 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
* <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* directory of this source tree.
*/
package com.facebook.react.tests;
import android.view.View;
import com.facebook.react.testing.ReactInstanceSpecForTest;
import com.facebook.react.testing.ReactAppInstrumentationTestCase;
import com.facebook.react.testing.ReactInstanceSpecForTest;
import com.facebook.react.testing.SingleTouchGestureGenerator;
import com.facebook.react.testing.StringRecordingModule;
/**
* This test is to verify that touch events bubbles up to the right handler. We emulate couple
* of different gestures on top of the application reflecting following layout:
* This test is to verify that touch events bubbles up to the right handler. We emulate couple of
* different gestures on top of the application reflecting following layout:
*
* +---------------------------------------------------------------------------------------+
* | |
* | +----------------------------------------------------------------------------------+ |
* | | +-------------+ +----------------+ | |
* | | | +---+ | | | | |
* | | | | A | | | | | |
* | | | +---+ | | C | | |
* | | | {B} | | | | |
* | | | | {D} | | | |
* | | +-------------+ +----------------+ | |
* | | | |
* | | | |
* | +----------------------------------------------------------------------------------+ |
* |
* | +----------------------------------------------------------------------------------+ |
* | | | |
* | | | |
* | | | |
* | | {E} | |
* | | | |
* | | | |
* | +----------------------------------------------------------------------------------+ |
* <p>+---------------------------------------------------------------------------------------+ | |
* | +----------------------------------------------------------------------------------+ | | |
* +-------------+ +----------------+ | | | | | +---+ | | | | | | | | | A | | | | | | | | | +---+ |
* | C | | | | | | {B} | | | | | | | | | {D} | | | | | | +-------------+ +----------------+ | | | |
* | | | | | | |
* +----------------------------------------------------------------------------------+ | | |
* +----------------------------------------------------------------------------------+ | | | | | |
* | | | | | | | | | {E} | | | | | | | | | | |
* +----------------------------------------------------------------------------------+ |
* +---------------------------------------------------------------------------------------+
*
* 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.
* View with names in brackets (e.g. {D}) have touch handlers set whereas all other views are not
* declared to handler touch events.
* <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. View with names in brackets (e.g. {D}) have touch
* handlers set whereas all other views are not declared to handler touch events.
*/
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
* 2) Simulate touch event at view C, expect {D} touch handler to fire
* 1) Simulate touch event at view A, expect {B} touch handler to fire 2) Simulate touch event at
* view C, expect {D} touch handler to fire
*/
public void testSimpleClickAtInnerElements() {
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
* touch handler to fire
* 2) Do the same with view C and {D}
* touch handler to fire 2) Do the same with view C and {D}
*/
public void testDownOnInnerUpOnTouchableParent() {
View innerButton = getViewByTestId("A");
@ -151,7 +134,6 @@ public class CatalystTouchBubblingTestCase extends ReactAppInstrumentationTestCa
@Override
protected ReactInstanceSpecForTest createReactInstanceSpecForTest() {
return new ReactInstanceSpecForTest()
.addNativeModule(mRecordingModule);
return new ReactInstanceSpecForTest().addNativeModule(mRecordingModule);
}
}

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

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

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

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

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

@ -1,20 +1,16 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
* <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* directory of this source tree.
*/
package com.facebook.react.tests;
import android.view.View;
import com.facebook.react.testing.ReactAppInstrumentationTestCase;
import com.facebook.react.testing.ReactInstanceSpecForTest;
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 {
private StringRecordingModule mStringRecordingModule;
@ -32,15 +28,19 @@ public class ImageErrorTestCase extends ReactAppInstrumentationTestCase {
Thread.sleep(3000);
assertEquals(3, mStringRecordingModule.getCalls().size());
assertEquals("Got error: Unsupported uri scheme! Uri is: ", mStringRecordingModule.getCalls().get(0));
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));
assertEquals(
"Got error: Unsupported uri scheme! Uri is: ", mStringRecordingModule.getCalls().get(0));
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
protected ReactInstanceSpecForTest createReactInstanceSpecForTest() {
mStringRecordingModule = new StringRecordingModule();
return super.createReactInstanceSpecForTest()
.addNativeModule(mStringRecordingModule);
return super.createReactInstanceSpecForTest().addNativeModule(mStringRecordingModule);
}
}

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

@ -1,18 +1,15 @@
/**
* Copyright (c) 2014-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
* <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* directory of this source tree.
*/
package com.facebook.react.tests;
import android.view.View;
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 {
@Override

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

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

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

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

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

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

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

@ -1,19 +1,16 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
* <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* directory of this source tree.
*/
package com.facebook.react.tests;
import com.facebook.react.testing.ReactAppInstrumentationTestCase;
import com.facebook.react.testing.ReactInstanceSpecForTest;
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 {
private StringRecordingModule mStringRecordingModule;
@ -23,9 +20,7 @@ public class LayoutEventsTestCase extends ReactAppInstrumentationTestCase {
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() {
assertEquals(3, mStringRecordingModule.getCalls().size());
assertEquals("10,10-100x100", mStringRecordingModule.getCalls().get(0));
@ -36,7 +31,6 @@ public class LayoutEventsTestCase extends ReactAppInstrumentationTestCase {
@Override
protected ReactInstanceSpecForTest createReactInstanceSpecForTest() {
mStringRecordingModule = new StringRecordingModule();
return super.createReactInstanceSpecForTest()
.addNativeModule(mStringRecordingModule);
return super.createReactInstanceSpecForTest().addNativeModule(mStringRecordingModule);
}
}

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

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

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

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

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

@ -1,25 +1,19 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
* <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* directory of this source tree.
*/
package com.facebook.react.tests;
import java.util.ArrayList;
import android.view.View;
import android.widget.HorizontalScrollView;
import com.facebook.react.testing.AbstractScrollViewTestCase;
import com.facebook.react.testing.SingleTouchGestureGenerator;
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 {
@Override
@ -61,8 +55,7 @@ public class ReactHorizontalScrollViewTestCase extends AbstractScrollViewTestCas
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 no item click event fired",
mScrollListenerModule.getItemsPressed().isEmpty());
"Expected no item click event fired", mScrollListenerModule.getItemsPressed().isEmpty());
assertEquals(
"Expected last offset to be offset of scroll view",
PixelUtil.toDIPFromPixel(scrollView.getScrollX()),
@ -103,9 +96,7 @@ public class ReactHorizontalScrollViewTestCase extends AbstractScrollViewTestCas
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 {
HorizontalScrollView scrollView = getViewAtPath(0);
ScrollViewTestModule jsModule =

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

@ -1,29 +1,26 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
* <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* directory of this source tree.
*/
package com.facebook.react.tests;
import java.util.ArrayList;
import java.util.List;
import android.graphics.Color;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
import android.widget.TextView;
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.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.ReactDropdownPickerManager;
import com.facebook.react.views.picker.ReactPicker;
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}
@ -34,7 +31,9 @@ public class ReactPickerTestCase extends ReactAppInstrumentationTestCase {
private static interface PickerAndroidTestModule extends JavaScriptModule {
public void selectItem(int position);
public void setMode(String mode);
public void setPrimaryColor(String color);
}
@ -66,8 +65,7 @@ public class ReactPickerTestCase extends ReactAppInstrumentationTestCase {
@Override
protected ReactInstanceSpecForTest createReactInstanceSpecForTest() {
mRecordingModule = new PickerAndroidRecordingModule();
return super.createReactInstanceSpecForTest()
.addNativeModule(mRecordingModule);
return super.createReactInstanceSpecForTest().addNativeModule(mRecordingModule);
}
public void testBasicProperties() {
@ -88,29 +86,22 @@ public class ReactPickerTestCase extends ReactAppInstrumentationTestCase {
assertEquals(Color.GREEN, ((TextView) adapter.getView(1, null, null)).getCurrentTextColor());
assertEquals(Color.BLUE, ((TextView) adapter.getView(2, null, null)).getCurrentTextColor());
assertEquals(
Color.RED,
((TextView) adapter.getDropDownView(0, null, null)).getCurrentTextColor());
Color.RED, ((TextView) adapter.getDropDownView(0, null, null)).getCurrentTextColor());
assertEquals(
Color.GREEN,
((TextView) adapter.getDropDownView(1, null, null)).getCurrentTextColor());
Color.GREEN, ((TextView) adapter.getDropDownView(1, null, null)).getCurrentTextColor());
assertEquals(
Color.BLUE,
((TextView) adapter.getDropDownView(2, null, null)).getCurrentTextColor());
Color.BLUE, ((TextView) adapter.getDropDownView(2, null, null)).getCurrentTextColor());
getTestModule().setPrimaryColor("black");
waitForBridgeAndUIIdle();
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(2, null, null)).getCurrentTextColor());
assertEquals(
Color.RED,
((TextView) adapter.getDropDownView(0, null, null)).getCurrentTextColor());
Color.RED, ((TextView) adapter.getDropDownView(0, null, null)).getCurrentTextColor());
assertEquals(
Color.GREEN,
((TextView) adapter.getDropDownView(1, null, null)).getCurrentTextColor());
Color.GREEN, ((TextView) adapter.getDropDownView(1, null, null)).getCurrentTextColor());
assertEquals(
Color.BLUE,
((TextView) adapter.getDropDownView(2, null, null)).getCurrentTextColor());
Color.BLUE, ((TextView) adapter.getDropDownView(2, null, null)).getCurrentTextColor());
}
public void testDropdownPicker() {
@ -176,9 +167,8 @@ public class ReactPickerTestCase extends ReactAppInstrumentationTestCase {
updateFirstSpinnerAndCheckLastSpinnerMatches(2);
}
private void updateFirstSpinnerAndCheckLastSpinnerMatches(
final int indexToSelect
) throws Throwable {
private void updateFirstSpinnerAndCheckLastSpinnerMatches(final int indexToSelect)
throws Throwable {
// 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.
runTestOnUiThread(
@ -202,5 +192,4 @@ public class ReactPickerTestCase extends ReactAppInstrumentationTestCase {
private PickerAndroidTestModule getTestModule() {
return getReactContext().getCatalystInstance().getJSModule(PickerAndroidTestModule.class);
}
}

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

@ -1,25 +1,19 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
* <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* directory of this source tree.
*/
package com.facebook.react.tests;
import java.util.ArrayList;
import android.view.View;
import android.widget.ScrollView;
import com.facebook.react.testing.AbstractScrollViewTestCase;
import com.facebook.react.testing.SingleTouchGestureGenerator;
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 {
@Override
@ -61,8 +55,7 @@ public class ReactScrollViewTestCase extends AbstractScrollViewTestCase {
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 no item click event fired",
mScrollListenerModule.getItemsPressed().isEmpty());
"Expected no item click event fired", mScrollListenerModule.getItemsPressed().isEmpty());
assertEquals(
"Expected last offset to be offset of scroll view",
PixelUtil.toDIPFromPixel(scrollView.getScrollY()),
@ -104,9 +97,7 @@ public class ReactScrollViewTestCase extends AbstractScrollViewTestCase {
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 {
ScrollView scrollView = getViewAtPath(0);
ScrollViewTestModule jsModule =

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

@ -28,15 +28,9 @@ public class ReactDebugOverlayTags {
"UI Manager View Operations (requires restart\nwarning: this is spammy)",
Color.CYAN);
public static final DebugOverlayTag FABRIC_UI_MANAGER =
new DebugOverlayTag(
"FabricUIManager",
"Fabric UI Manager View Operations",
Color.CYAN);
new DebugOverlayTag("FabricUIManager", "Fabric UI Manager View Operations", Color.CYAN);
public static final DebugOverlayTag FABRIC_RECONCILER =
new DebugOverlayTag(
"FabricReconciler",
"Reconciler for Fabric",
Color.CYAN);
new DebugOverlayTag("FabricReconciler", "Reconciler for Fabric", Color.CYAN);
public static final DebugOverlayTag RELAY =
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.
*
* 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
* on. In the common case when this is called by Countable#finalize(), this will be called on the
* system finalizer thread. If you manually call dispose on the Java object, the native object
* <p>{@link #dispose} deletes the corresponding native object on whatever thread the method is
* called on. In the common case when this is called by Countable#finalize(), this will be called on
* the system finalizer thread. If you manually call dispose on the Java object, the native object
* will be deleted synchronously on that thread.
*/
@DoNotStrip
@ -26,8 +26,7 @@ public class Countable {
}
// Private C++ instance
@DoNotStrip
private long mInstance = 0;
@DoNotStrip private long mInstance = 0;
public native void dispose();

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

@ -8,9 +8,7 @@ package com.facebook.jni;
import com.facebook.proguard.annotations.DoNotStrip;
import com.facebook.soloader.SoLoader;
/**
* Utility class to determine CPU capabilities
*/
/** Utility class to determine CPU capabilities */
@DoNotStrip
public class CpuCapabilitiesJni {
@ -26,5 +24,4 @@ public class CpuCapabilitiesJni {
@DoNotStrip
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.
*
* 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
* {@link Destructor#destruct()} method.
* <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 {@link
* Destructor#destruct()} method.
*
* The underlying thread in DestructorThread starts when the first Destructor is constructed
* and then runs indefinitely.
* <p>The underlying thread in DestructorThread starts when the first Destructor is constructed and
* then runs indefinitely.
*/
public class DestructorThread {
@ -48,6 +48,7 @@ public class DestructorThread {
private static DestructorList sDestructorList;
/** A thread safe stack where new Destructors are placed before being add to sDestructorList. */
private static DestructorStack sDestructorStack;
private static ReferenceQueue sReferenceQueue;
private static Thread sThread;
@ -55,7 +56,8 @@ public class DestructorThread {
sDestructorStack = new DestructorStack();
sReferenceQueue = new ReferenceQueue();
sDestructorList = new DestructorList();
sThread = new Thread("HybridData DestructorThread") {
sThread =
new Thread("HybridData DestructorThread") {
@Override
public void run() {
while (true) {

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

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

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

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

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

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

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

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

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

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

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

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

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

@ -1,24 +1,22 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
* <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* directory of this source tree.
*/
package com.facebook.proguard.annotations;
import static java.lang.annotation.RetentionPolicy.CLASS;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
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.
*
* 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})
@Retention(CLASS)
public @interface DoNotStrip {
}
public @interface DoNotStrip {}

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

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

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

@ -20,7 +20,6 @@ import java.util.ListIterator;
import java.util.Map;
import java.util.Set;
import javax.annotation.Nullable;
import com.facebook.react.TurboReactPackage;
/**
* {@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<>();
for (ReactPackage reactPackage : mChildReactPackages) {
/**
* For now, we eagerly initialize the NativeModules inside TurboReactPackages.
* Ultimately, we should turn CompositeReactPackage into a TurboReactPackage
* and remove this eager initialization.
* For now, we eagerly initialize the NativeModules inside TurboReactPackages. Ultimately, we
* should turn CompositeReactPackage into a TurboReactPackage and remove this eager
* initialization.
*
* TODO: T45627020
* <p>TODO: T45627020
*/
if (reactPackage instanceof TurboReactPackage) {
TurboReactPackage turboReactPackage = (TurboReactPackage) reactPackage;

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

@ -6,6 +6,7 @@
*/
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_START;
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.model.ReactModuleInfo;
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.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.Timing;
import com.facebook.react.modules.debug.DevSettingsModule;
import com.facebook.react.modules.debug.SourceCodeModule;
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.ViewManager;
import com.facebook.systrace.Systrace;
import java.util.Collections;
import javax.annotation.Nullable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static com.facebook.react.bridge.ReactMarkerConstants.*;
import javax.annotation.Nullable;
/**
* 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.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
* <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* directory of this source tree.
*/
package com.facebook.react;
import com.facebook.react.bridge.ModuleSpec;
@ -27,12 +26,10 @@ import javax.inject.Provider;
nativeModules = {
JSCHeapCapture.class,
JSDevSupport.class,
}
)
})
/* package */ class DebugCorePackage extends LazyReactPackage {
DebugCorePackage() {
}
DebugCorePackage() {}
@Override
public List<ModuleSpec> getNativeModules(final ReactApplicationContext reactContext) {

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

@ -5,13 +5,10 @@
package com.facebook.react;
import com.facebook.react.bridge.NativeModule;
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> {
private final NativeModule mModule;

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

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

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

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

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

@ -13,9 +13,7 @@ import java.util.Collections;
import java.util.LinkedHashSet;
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 {
private final Set<MemoryPressureListener> mListeners =
Collections.synchronizedSet(new LinkedHashSet<MemoryPressureListener>());
@ -28,16 +26,12 @@ public class MemoryPressureRouter implements ComponentCallbacks2 {
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) {
mListeners.add(listener);
}
/**
* Remove a listener previously added with {@link #addMemoryPressureListener}.
*/
/** Remove a listener previously added with {@link #addMemoryPressureListener}. */
public void removeMemoryPressureListener(MemoryPressureListener listener) {
mListeners.remove(listener);
}
@ -48,12 +42,10 @@ public class MemoryPressureRouter implements ComponentCallbacks2 {
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
}
public void onConfigurationChanged(Configuration newConfig) {}
@Override
public void onLowMemory() {
}
public void onLowMemory() {}
private void dispatchMemoryPressure(int level) {
// 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
// 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;
}
mModules.put(name, moduleHolder);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

@ -1,10 +1,9 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
* <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* directory of this source tree.
*/
package com.facebook.react;
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.BUILD_NATIVE_MODULE_REGISTRY_END;
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_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.SETUP_REACT_CONTEXT_END;
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.uimanager.common.UIManagerType.FABRIC;
import static com.facebook.systrace.Systrace.TRACE_TAG_REACT_APPS;
@ -38,9 +37,9 @@ import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Process;
import androidx.core.view.ViewCompat;
import android.util.Log;
import android.view.View;
import androidx.core.view.ViewCompat;
import com.facebook.common.logging.FLog;
import com.facebook.debug.holder.PrinterHolder;
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
* catalyst instance using {@link ReactPackage} and keeps track of the lifecycle of that
* instance. It also sets up connection between the instance and developers support functionality
* of the framework.
* catalyst instance using {@link ReactPackage} and keeps track of the lifecycle of that instance.
* It also sets up connection between the instance and developers support functionality of the
* 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).
*
* The lifecycle of the instance of {@link ReactInstanceManager} should be bound to the
* activity that owns the {@link ReactRootView} that is used to render react application using this
* instance manager (see {@link ReactRootView#startReactApplication}). It's required to pass owning
* <p>The lifecycle of the instance of {@link ReactInstanceManager} should be bound to the activity
* that owns the {@link ReactRootView} that is used to render react application using this instance
* manager (see {@link ReactRootView#startReactApplication}). It's required to pass owning
* activity's lifecycle events to the instance manager (see {@link #onHostPause}, {@link
* #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
public class ReactInstanceManager {
private static final String TAG = ReactInstanceManager.class.getSimpleName();
/**
* Listener interface for react instance events.
*/
/** Listener interface for react instance events. */
public interface ReactInstanceEventListener {
/**
@ -138,8 +135,8 @@ public class ReactInstanceManager {
void onReactContextInitialized(ReactContext context);
}
private final Set<ReactRoot> mAttachedReactRoots = Collections.synchronizedSet(
new HashSet<ReactRoot>());
private final Set<ReactRoot> mAttachedReactRoots =
Collections.synchronizedSet(new HashSet<ReactRoot>());
private volatile LifecycleState mLifecycleState;
@ -176,8 +173,7 @@ public class ReactInstanceManager {
private final JSBundleLoader mJsBundleLoader;
public ReactContextInitParams(
JavaScriptExecutorFactory jsExecutorFactory,
JSBundleLoader jsBundleLoader) {
JavaScriptExecutorFactory jsExecutorFactory, JSBundleLoader jsBundleLoader) {
mJsExecutorFactory = Assertions.assertNotNull(jsExecutorFactory);
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() {
return new ReactInstanceManagerBuilder();
}
@ -326,10 +320,10 @@ public class ReactInstanceManager {
/**
* Trigger react context initialization asynchronously in a background async task. This enables
* applications to pre-load the application JS, and execute global code before
* {@link ReactRootView} is available and measured.
* applications to pre-load the application JS, and execute global code before {@link
* ReactRootView} is available and measured.
*
* Called from UI thread.
* <p>Called from UI thread.
*/
@ThreadConfined(UI)
public void createReactContextInBackground() {
@ -351,8 +345,8 @@ public class ReactInstanceManager {
public void recreateReactContextInBackground() {
Assertions.assertCondition(
mHasStartedCreatingInitialContext,
"recreateReactContextInBackground should only be called after the initial " +
"createReactContextInBackground call.");
"recreateReactContextInBackground should only be called after the initial "
+ "createReactContextInBackground call.");
recreateReactContextInBackgroundInner();
}
@ -367,8 +361,8 @@ public class ReactInstanceManager {
final DeveloperSettings devSettings = mDevSupportManager.getDevSettings();
// If remote JS debugging is enabled, load from dev server.
if (mDevSupportManager.hasUpToDateJSBundleInCache() &&
!devSettings.isRemoteJSDebugEnabled()) {
if (mDevSupportManager.hasUpToDateJSBundleInCache()
&& !devSettings.isRemoteJSDebugEnabled()) {
// If there is a up-to-date bundle downloaded from server,
// with remote JS debugging disabled, always use that.
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)
public void onNewIntent(Intent intent) {
UiThreadUtil.assertOnUiThread();
@ -501,8 +493,8 @@ public class ReactInstanceManager {
/**
* 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
* always be the foreground activity that would be returned by
* {@link ReactContext#getCurrentActivity()}.
* always be the foreground activity that would be returned by {@link
* ReactContext#getCurrentActivity()}.
*
* @param activity the activity being paused
*/
@ -511,19 +503,22 @@ public class ReactInstanceManager {
Assertions.assertNotNull(mCurrentActivity);
Assertions.assertCondition(
activity == mCurrentActivity,
"Pausing an activity that is not the current activity, this is incorrect! " +
"Current activity: " + mCurrentActivity.getClass().getSimpleName() + " " +
"Paused activity: " + activity.getClass().getSimpleName());
"Pausing an activity that is not the current activity, this is incorrect! "
+ "Current activity: "
+ mCurrentActivity.getClass().getSimpleName()
+ " "
+ "Paused activity: "
+ activity.getClass().getSimpleName());
onHostPause();
}
/**
* 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
* from the activity instance that owns this particular instance of {@link
* ReactInstanceManager}, so that once this instance receive {@link #onHostDestroy} event it
* will clear the reference to that defaultBackButtonImpl.
* <p>This method retains an instance to provided mDefaultBackButtonImpl. Thus it's important to
* pass from the activity instance that owns this particular instance of {@link
* ReactInstanceManager}, so that once this instance receive {@link #onHostDestroy} event it will
* clear the reference to that defaultBackButtonImpl.
*
* @param defaultBackButtonImpl a {@link DefaultHardwareBackBtnHandler} from an Activity that owns
* this instance of {@link ReactInstanceManager}.
@ -536,9 +531,7 @@ public class ReactInstanceManager {
onHostResume(activity);
}
/**
* Use this method when the activity resumes.
*/
/** Use this method when the activity resumes. */
@ThreadConfined(UI)
public void onHostResume(Activity activity) {
UiThreadUtil.assertOnUiThread();
@ -558,7 +551,8 @@ public class ReactInstanceManager {
// We check if activity is attached to window by checking if decor view is attached
final View decorView = mCurrentActivity.getWindow().getDecorView();
if (!ViewCompat.isAttachedToWindow(decorView)) {
decorView.addOnAttachStateChangeListener(new View.OnAttachStateChangeListener() {
decorView.addOnAttachStateChangeListener(
new View.OnAttachStateChangeListener() {
@Override
public void onViewAttachedToWindow(View v) {
// 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)
public void destroy() {
UiThreadUtil.assertOnUiThread();
@ -655,9 +647,9 @@ public class ReactInstanceManager {
ReactContext currentContext = getCurrentReactContext();
if (currentContext != null) {
// we currently don't have an onCreate callback so we call onResume for both transitions
if (force ||
mLifecycleState == LifecycleState.BEFORE_RESUME ||
mLifecycleState == LifecycleState.BEFORE_CREATE) {
if (force
|| mLifecycleState == LifecycleState.BEFORE_RESUME
|| mLifecycleState == LifecycleState.BEFORE_CREATE) {
currentContext.onHostResume(mCurrentActivity);
}
}
@ -729,9 +721,9 @@ public class ReactInstanceManager {
* 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
* 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.
* This reactRoot will then be tracked by this manager and in case of catalyst instance restart it will
* be re-attached.
* with the provided reactRoot reactRoot will be started asynchronously, i.e this method won't
* block. This reactRoot will then be tracked by this manager and in case of catalyst instance
* restart it will be re-attached.
*/
@ThreadConfined(UI)
public void attachRootView(ReactRoot reactRoot) {
@ -742,7 +734,8 @@ public class ReactInstanceManager {
clearReactRoot(reactRoot);
// 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();
if (mCreateReactContextThread == null && currentContext != null) {
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(
ReactApplicationContext catalystApplicationContext) {
ReactMarker.logMarker(CREATE_VIEW_MANAGERS_START);
@ -831,7 +822,8 @@ public class ReactInstanceManager {
synchronized (mPackages) {
Set<String> uniqueNames = new HashSet<>();
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())
.flush();
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) {
mReactInstanceEventListeners.add(listener);
}
/**
* Remove a listener previously added with {@link #addReactInstanceEventListener}.
*/
/** Remove a listener previously added with {@link #addReactInstanceEventListener}. */
public void removeReactInstanceEventListener(ReactInstanceEventListener listener) {
mReactInstanceEventListeners.remove(listener);
}
@ -891,10 +879,10 @@ public class ReactInstanceManager {
private void onJSBundleLoadedFromServer(@Nullable NativeDeltaClient nativeDeltaClient) {
Log.d(ReactConstants.TAG, "ReactInstanceManager.onJSBundleLoadedFromServer()");
JSBundleLoader bundleLoader = nativeDeltaClient == null
JSBundleLoader bundleLoader =
nativeDeltaClient == null
? JSBundleLoader.createCachedBundleFromNetworkLoader(
mDevSupportManager.getSourceUrl(),
mDevSupportManager.getDownloadedJSBundleFile())
mDevSupportManager.getSourceUrl(), mDevSupportManager.getDownloadedJSBundleFile())
: JSBundleLoader.createDeltaFromNetworkLoader(
mDevSupportManager.getSourceUrl(), nativeDeltaClient);
@ -903,14 +891,12 @@ public class ReactInstanceManager {
@ThreadConfined(UI)
private void recreateReactContextInBackground(
JavaScriptExecutorFactory jsExecutorFactory,
JSBundleLoader jsBundleLoader) {
JavaScriptExecutorFactory jsExecutorFactory, JSBundleLoader jsBundleLoader) {
Log.d(ReactConstants.TAG, "ReactInstanceManager.recreateReactContextInBackground()");
UiThreadUtil.assertOnUiThread();
final ReactContextInitParams initParams = new ReactContextInitParams(
jsExecutorFactory,
jsBundleLoader);
final ReactContextInitParams initParams =
new ReactContextInitParams(jsExecutorFactory, jsBundleLoader);
if (mCreateReactContextThread == null) {
runCreateReactContextOnNewThread(initParams);
} 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;
try {
@ -1009,7 +996,6 @@ public class ReactInstanceManager {
catalystInstance.initialize();
mDevSupportManager.onNewReactContextCreated(reactContext);
mMemoryPressureRouter.addMemoryPressureListener(catalystInstance);
moveReactContextToCurrentLifecycleState();
@ -1057,28 +1043,30 @@ public class ReactInstanceManager {
private void attachRootViewToInstance(final ReactRoot reactRoot) {
Log.d(ReactConstants.TAG, "ReactInstanceManager.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();
final int rootTag = uiManager.addRootView(
final int rootTag =
uiManager.addRootView(
reactRoot.getRootViewGroup(),
initialProperties == null ?
new WritableNativeMap() : Arguments.fromBundle(initialProperties),
initialProperties == null
? new WritableNativeMap()
: Arguments.fromBundle(initialProperties),
reactRoot.getInitialUITemplate());
reactRoot.setRootViewTag(rootTag);
if (reactRoot.getUIManagerType() == FABRIC) {
// Fabric requires to call updateRootLayoutSpecs before starting JS Application,
// 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);
} else {
reactRoot.runApplication();
}
Systrace.beginAsyncSection(
TRACE_TAG_REACT_JAVA_BRIDGE,
"pre_rootView.onAttachedToReactInstance",
rootTag);
TRACE_TAG_REACT_JAVA_BRIDGE, "pre_rootView.onAttachedToReactInstance", rootTag);
UiThreadUtil.runOnUiThread(
new Runnable() {
@Override
@ -1091,19 +1079,18 @@ public class ReactInstanceManager {
Systrace.endSection(TRACE_TAG_REACT_JAVA_BRIDGE);
}
private void detachViewFromInstance(
ReactRoot reactRoot,
CatalystInstance catalystInstance) {
private void detachViewFromInstance(ReactRoot reactRoot, CatalystInstance catalystInstance) {
Log.d(ReactConstants.TAG, "ReactInstanceManager.detachViewFromInstance()");
UiThreadUtil.assertOnUiThread();
if (reactRoot.getUIManagerType() == FABRIC) {
catalystInstance.getJSModule(ReactFabric.class)
catalystInstance
.getJSModule(ReactFabric.class)
.unmountComponentAtNode(reactRoot.getRootViewTag());
} else {
catalystInstance.getJSModule(AppRegistry.class)
catalystInstance
.getJSModule(AppRegistry.class)
.unmountApplicationComponentAtRootTag(reactRoot.getRootViewTag());
}
}
private void tearDownReactContext(ReactContext reactContext) {
@ -1124,24 +1111,23 @@ public class ReactInstanceManager {
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(
JavaScriptExecutor jsExecutor,
JSBundleLoader jsBundleLoader) {
JavaScriptExecutor jsExecutor, JSBundleLoader jsBundleLoader) {
Log.d(ReactConstants.TAG, "ReactInstanceManager.createReactContext()");
ReactMarker.logMarker(CREATE_REACT_CONTEXT_START, jsExecutor.getName());
final ReactApplicationContext reactContext = new ReactApplicationContext(mApplicationContext);
NativeModuleCallExceptionHandler exceptionHandler = mNativeModuleCallExceptionHandler != null
NativeModuleCallExceptionHandler exceptionHandler =
mNativeModuleCallExceptionHandler != null
? mNativeModuleCallExceptionHandler
: mDevSupportManager;
reactContext.setNativeModuleCallExceptionHandler(exceptionHandler);
NativeModuleRegistry nativeModuleRegistry = processPackages(reactContext, mPackages, false);
CatalystInstanceImpl.Builder catalystInstanceBuilder = new CatalystInstanceImpl.Builder()
CatalystInstanceImpl.Builder catalystInstanceBuilder =
new CatalystInstanceImpl.Builder()
.setReactQueueConfigurationSpec(ReactQueueConfigurationSpec.createDefault())
.setJSExecutor(jsExecutor)
.setRegistry(nativeModuleRegistry)
@ -1162,11 +1148,13 @@ public class ReactInstanceManager {
reactContext.initializeWithInstance(catalystInstance);
if (mJSIModulePackage != null) {
catalystInstance.addJSIModules(mJSIModulePackage
.getJSIModules(reactContext, catalystInstance.getJavaScriptContextHolder()));
catalystInstance.addJSIModules(
mJSIModulePackage.getJSIModules(
reactContext, catalystInstance.getJavaScriptContextHolder()));
if (ReactFeatureFlags.useTurboModules) {
catalystInstance.setTurboModuleManager(catalystInstance.getJSIModule(JSIModuleType.TurboModuleManager));
catalystInstance.setTurboModuleManager(
catalystInstance.getJSIModule(JSIModuleType.TurboModuleManager));
}
}
if (mBridgeIdleDebugListener != null) {
@ -1187,9 +1175,8 @@ public class ReactInstanceManager {
ReactApplicationContext reactContext,
List<ReactPackage> packages,
boolean checkAndUpdatePackageMembership) {
NativeModuleRegistryBuilder nativeModuleRegistryBuilder = new NativeModuleRegistryBuilder(
reactContext,
this);
NativeModuleRegistryBuilder nativeModuleRegistryBuilder =
new NativeModuleRegistryBuilder(reactContext, this);
ReactMarker.logMarker(PROCESS_PACKAGES_START);
@ -1226,8 +1213,7 @@ public class ReactInstanceManager {
}
private void processPackage(
ReactPackage reactPackage,
NativeModuleRegistryBuilder nativeModuleRegistryBuilder) {
ReactPackage reactPackage, NativeModuleRegistryBuilder nativeModuleRegistryBuilder) {
SystraceMessage.beginSection(TRACE_TAG_REACT_JAVA_BRIDGE, "processPackage")
.arg("className", reactPackage.getClass().getSimpleName())
.flush();

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

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

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

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

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

@ -1,10 +1,9 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
* <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* directory of this source tree.
*/
package com.facebook.react;
import android.app.Application;
@ -32,9 +31,7 @@ public abstract class ReactNativeHost {
mApplication = application;
}
/**
* Get the current {@link ReactInstanceManager} instance, or create one.
*/
/** Get the current {@link ReactInstanceManager} instance, or create one. */
public ReactInstanceManager getReactInstanceManager() {
if (mReactInstanceManager == null) {
ReactMarker.logMarker(ReactMarkerConstants.GET_REACT_INSTANCE_MANAGER_START);
@ -65,7 +62,8 @@ public abstract class ReactNativeHost {
protected ReactInstanceManager createReactInstanceManager() {
ReactMarker.logMarker(ReactMarkerConstants.BUILD_REACT_INSTANCE_MANAGER_START);
ReactInstanceManagerBuilder builder = ReactInstanceManager.builder()
ReactInstanceManagerBuilder builder =
ReactInstanceManager.builder()
.setApplication(mApplication)
.setJSMainModulePath(getJSMainModuleName())
.setUseDeveloperSupport(getUseDeveloperSupport())
@ -90,17 +88,12 @@ public abstract class ReactNativeHost {
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() {
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() {
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
* 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() {
return new UIImplementationProvider();
}
protected @Nullable
JSIModulePackage getJSIModulePackage() {
protected @Nullable JSIModulePackage getJSIModulePackage() {
return null;
}
/**
* Returns the name of the main module. Determines the URL used to fetch the JS bundle
* from the packager server. It is only used when dev support is enabled.
* This is the first file to be executed once the {@link ReactInstanceManager} is created.
* e.g. "index.android"
* Returns the name of the main module. Determines the URL used to fetch the JS bundle from the
* packager server. It is only used when dev support is enabled. This is the first file to be
* executed once the {@link ReactInstanceManager} is created. e.g. "index.android"
*/
protected String getJSMainModuleName() {
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
* from a custom path. By default it is loaded from Android assets, from a path specified
* by {@link getBundleAssetName}.
* e.g. "file://sdcard/myapp_cache/index.android.bundle"
* from a custom path. By default it is loaded from Android assets, from a path specified by
* {@link getBundleAssetName}. e.g. "file://sdcard/myapp_cache/index.android.bundle"
*/
protected @Nullable String getJSBundleFile() {
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
* the bundle, the app will only work with {@code getUseDeveloperSupport} enabled and will
* always try to load the JS bundle from the packager server.
* e.g. "index.android.bundle"
* the bundle, the app will only work with {@code getUseDeveloperSupport} enabled and will always
* try to load the JS bundle from the packager server. e.g. "index.android.bundle"
*/
protected @Nullable String getBundleAssetName() {
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();
/**
* Returns a list of {@link ReactPackage} used by the app.
* You'll most likely want to return at least the {@code MainReactPackage}.
* If your app uses additional views or modules besides the default ones,
* you'll want to include more packages here.
* Returns a list of {@link ReactPackage} used by the app. You'll most likely want to return at
* least the {@code MainReactPackage}. If your app uses additional views or modules besides the
* default ones, you'll want to include more packages here.
*/
protected abstract List<ReactPackage> getPackages();
}

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

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

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

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

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

@ -5,11 +5,10 @@
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 {
void startProcessPackage();
void endProcessPackage();
}

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

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

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

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

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

@ -1,10 +1,9 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
* <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* directory of this source tree.
*/
package com.facebook.react;
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.
* 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
* implementing package how to interpret the name.

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

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

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

@ -1,22 +1,17 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
* <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* directory of this source tree.
*/
package com.facebook.react.animated;
import com.facebook.infer.annotation.Assertions;
import java.util.ArrayList;
import java.util.List;
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 {
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
* given node that can then be used to calculate current node's value in {@link #update}.
* In that case it is important to also override {@link #onDetachedFromNode} to clear that
* reference once current node gets detached.
* given node that can then be used to calculate current node's value in {@link #update}. In that
* case it is important to also override {@link #onDetachedFromNode} to clear that reference once
* current node gets detached.
*/
public void onAttachedToNode(AnimatedNode parent) {
}
public void onAttachedToNode(AnimatedNode parent) {}
/**
* See {@link #onAttachedToNode}
*/
public void onDetachedFromNode(AnimatedNode parent) {
}
/** See {@link #onAttachedToNode} */
public void onDetachedFromNode(AnimatedNode parent) {}
/**
* 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
* 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.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
* <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* directory of this source tree.
*/
package com.facebook.react.animated;
/**
* Interface used to listen to {@link ValueAnimatedNode} updates.
*/
/** Interface used to listen to {@link ValueAnimatedNode} updates. */
public interface AnimatedNodeValueListener {
void onValueUpdate(double value);
}

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

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

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

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

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