下面列出了怎么用com.facebook.react.bridge.JavaOnlyMap的API类实例代码及写法,或者点击链接到github查看源代码。
public void collectViewUpdates(JavaOnlyMap propsMap) {
List<JavaOnlyMap> transforms = new ArrayList<>(mTransformConfigs.size());
for (TransformConfig transformConfig : mTransformConfigs) {
double value;
if (transformConfig instanceof AnimatedTransformConfig) {
int nodeTag = ((AnimatedTransformConfig) transformConfig).mNodeTag;
AnimatedNode node = mNativeAnimatedNodesManager.getNodeById(nodeTag);
if (node == null) {
throw new IllegalArgumentException("Mapped style node does not exists");
} else if (node instanceof ValueAnimatedNode) {
value = ((ValueAnimatedNode) node).getValue();
} else {
throw new IllegalArgumentException("Unsupported type of node used as a transform child " +
"node " + node.getClass());
}
} else {
value = ((StaticTransformConfig) transformConfig).mValue;
}
transforms.add(JavaOnlyMap.of(transformConfig.mProperty, value));
}
propsMap.putArray("transform", JavaOnlyArray.from(transforms));
}
@Test
public void testSelection() {
ReactEditText view = mManager.createViewInstance(mThemedContext);
view.setText("Need some text to select something...");
mManager.updateProperties(view, buildStyles());
assertThat(view.getSelectionStart()).isEqualTo(0);
assertThat(view.getSelectionEnd()).isEqualTo(0);
JavaOnlyMap selection = JavaOnlyMap.of("start", 5, "end", 10);
mManager.updateProperties(view, buildStyles("selection", selection));
assertThat(view.getSelectionStart()).isEqualTo(5);
assertThat(view.getSelectionEnd()).isEqualTo(10);
mManager.updateProperties(view, buildStyles("selection", null));
assertThat(view.getSelectionStart()).isEqualTo(5);
assertThat(view.getSelectionEnd()).isEqualTo(10);
}
@Test
public void testFontFamilyBoldItalicStyleApplied() {
UIManagerModule uiManager = getUIManagerModule();
ReactRootView rootView = createText(
uiManager,
JavaOnlyMap.of(
ViewProps.FONT_FAMILY, "sans-serif",
ViewProps.FONT_WEIGHT, "500",
ViewProps.FONT_STYLE, "italic"),
JavaOnlyMap.of(ReactRawTextShadowNode.PROP_TEXT, "test text"));
CustomStyleSpan customStyleSpan =
getSingleSpan((TextView) rootView.getChildAt(0), CustomStyleSpan.class);
assertThat(customStyleSpan.getFontFamily()).isEqualTo("sans-serif");
assertThat(customStyleSpan.getStyle() & Typeface.ITALIC).isNotZero();
assertThat(customStyleSpan.getWeight() & Typeface.BOLD).isNotZero();
}
@Test
public void testTextDecorationLineUnderlineApplied() {
UIManagerModule uiManager = getUIManagerModule();
ReactRootView rootView = createText(
uiManager,
JavaOnlyMap.of(ViewProps.TEXT_DECORATION_LINE, "underline"),
JavaOnlyMap.of(ReactRawTextShadowNode.PROP_TEXT, "test text"));
TextView textView = (TextView) rootView.getChildAt(0);
Spanned text = (Spanned) textView.getText();
UnderlineSpan underlineSpan = getSingleSpan(textView, UnderlineSpan.class);
StrikethroughSpan[] strikeThroughSpans =
text.getSpans(0, text.length(), StrikethroughSpan.class);
assertThat(underlineSpan instanceof UnderlineSpan).isTrue();
assertThat(strikeThroughSpans).hasSize(0);
}
@Test
public void testTextDecorationLineLineThroughApplied() {
UIManagerModule uiManager = getUIManagerModule();
ReactRootView rootView = createText(
uiManager,
JavaOnlyMap.of(ViewProps.TEXT_DECORATION_LINE, "line-through"),
JavaOnlyMap.of(ReactRawTextShadowNode.PROP_TEXT, "test text"));
TextView textView = (TextView) rootView.getChildAt(0);
Spanned text = (Spanned) textView.getText();
UnderlineSpan[] underlineSpans =
text.getSpans(0, text.length(), UnderlineSpan.class);
StrikethroughSpan strikeThroughSpan =
getSingleSpan(textView, StrikethroughSpan.class);
assertThat(underlineSpans).hasSize(0);
assertThat(strikeThroughSpan instanceof StrikethroughSpan).isTrue();
}
@Test
public void testTextDecorationLineUnderlineLineThroughApplied() {
UIManagerModule uiManager = getUIManagerModule();
ReactRootView rootView = createText(
uiManager,
JavaOnlyMap.of(ViewProps.TEXT_DECORATION_LINE, "underline line-through"),
JavaOnlyMap.of(ReactRawTextShadowNode.PROP_TEXT, "test text"));
UnderlineSpan underlineSpan =
getSingleSpan((TextView) rootView.getChildAt(0), UnderlineSpan.class);
StrikethroughSpan strikeThroughSpan =
getSingleSpan((TextView) rootView.getChildAt(0), StrikethroughSpan.class);
assertThat(underlineSpan instanceof UnderlineSpan).isTrue();
assertThat(strikeThroughSpan instanceof StrikethroughSpan).isTrue();
}
@Test
public void testAllOptions() {
final JavaOnlyMap options = new JavaOnlyMap();
options.putString("title", "Title");
options.putString("message", "Message");
options.putString("buttonPositive", "OK");
options.putString("buttonNegative", "Cancel");
options.putString("buttonNeutral", "Later");
options.putBoolean("cancelable", false);
mDialogModule.showAlert(options, null, null);
final AlertFragment fragment = getFragment();
assertNotNull("Fragment was not displayed", fragment);
assertEquals(false, fragment.isCancelable());
final AlertDialog dialog = (AlertDialog) fragment.getDialog();
assertEquals("OK", dialog.getButton(DialogInterface.BUTTON_POSITIVE).getText().toString());
assertEquals("Cancel", dialog.getButton(DialogInterface.BUTTON_NEGATIVE).getText().toString());
assertEquals("Later", dialog.getButton(DialogInterface.BUTTON_NEUTRAL).getText().toString());
}
@Before
public void prepareModules() throws Exception {
PowerMockito.mockStatic(Arguments.class);
Mockito.when(Arguments.createMap()).thenAnswer(new Answer<Object>() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
return new JavaOnlyMap();
}
});
mBytes = new byte[120];
new Random().nextBytes(mBytes);
mBlobModule = new BlobModule(ReactTestHelper.createCatalystContextForTest());
mBlobId = mBlobModule.store(mBytes);
}
@Test
public void testUpdateSimpleHierarchy() {
UIManagerModule uiManager = getUIManagerModule();
ViewGroup rootView = createSimpleTextHierarchy(uiManager, "Some text");
TextView textView = (TextView) rootView.getChildAt(0);
int rawTextTag = 3;
uiManager.updateView(
rawTextTag,
ReactRawTextManager.REACT_CLASS,
JavaOnlyMap.of(ReactRawTextShadowNode.PROP_TEXT, "New text"));
uiManager.onBatchComplete();
executePendingFrameCallbacks();
assertThat(textView.getText().toString()).isEqualTo("New text");
}
@Test
@Config(sdk = Build.VERSION_CODES.P)
public void testGetSecurityLevel_NoBiometry_api28() throws Exception {
// GIVE:
final ReactApplicationContext context = getRNContext();
final KeychainModule module = new KeychainModule(context);
final Promise mockPromise = mock(Promise.class);
// WHEN:
final JavaOnlyMap options = new JavaOnlyMap();
options.putString(Maps.ACCESS_CONTROL, AccessControl.DEVICE_PASSCODE);
module.getSecurityLevel(options, mockPromise);
// THEN:
verify(mockPromise).resolve(SecurityLevel.SECURE_HARDWARE.name());
}
/**
* Makes sure replaceExistingNonRootView by replacing a view with a new view that has a background
* color set.
*/
@Test
public void testReplaceExistingNonRootView() {
UIManagerModule uiManager = getUIManagerModule();
TestMoveDeleteHierarchy hierarchy = createMoveDeleteHierarchy(uiManager);
int newViewTag = 1234;
uiManager.createView(
newViewTag,
ReactViewManager.REACT_CLASS,
hierarchy.rootView,
JavaOnlyMap.of("backgroundColor", Color.RED));
uiManager.replaceExistingNonRootView(hierarchy.view2, newViewTag);
uiManager.onBatchComplete();
executePendingFrameCallbacks();
assertThat(hierarchy.nativeRootView.getChildCount()).isEqualTo(4);
assertThat(hierarchy.nativeRootView.getChildAt(2)).isInstanceOf(ReactViewGroup.class);
ReactViewGroup view = (ReactViewGroup) hierarchy.nativeRootView.getChildAt(2);
assertThat(view.getBackgroundColor()).isEqualTo(Color.RED);
}
@Test
public void testNativeAnimatedEventDoUpdate() {
int viewTag = 1000;
createSimpleAnimatedViewWithOpacity(viewTag, 0d);
mNativeAnimatedNodesManager.addAnimatedEventToView(viewTag, "topScroll", JavaOnlyMap.of(
"animatedValueTag", 1,
"nativeEventPath", JavaOnlyArray.of("contentOffset", "y")));
mNativeAnimatedNodesManager.onEventDispatch(createScrollEvent(viewTag, 10));
ArgumentCaptor<ReactStylesDiffMap> stylesCaptor =
ArgumentCaptor.forClass(ReactStylesDiffMap.class);
reset(mUIImplementationMock);
mNativeAnimatedNodesManager.runUpdates(nextFrameTime());
verify(mUIImplementationMock).synchronouslyUpdateViewOnUIThread(eq(viewTag), stylesCaptor.capture());
assertThat(stylesCaptor.getValue().getDouble("opacity", Double.NaN)).isEqualTo(10);
}
@Test
@Config(sdk = Build.VERSION_CODES.P)
public void testGetSecurityLevel_NoBiometry_NoSecuredHardware_api28() throws Exception {
// GIVE:
final ReactApplicationContext context = getRNContext();
final KeychainModule module = new KeychainModule(context);
final Promise mockPromise = mock(Promise.class);
// set key info - software method
provider.configuration.put("isInsideSecureHardware", false);
// WHEN:
final JavaOnlyMap options = new JavaOnlyMap();
options.putString(Maps.ACCESS_CONTROL, AccessControl.DEVICE_PASSCODE);
module.getSecurityLevel(options, mockPromise);
// THEN:
// expected AesCbc usage
assertThat(provider.mocks.get("KeyGenerator"), notNullValue());
assertThat(provider.mocks.get("KeyGenerator").get("AES"), notNullValue());
assertThat(provider.mocks.get("KeyPairGenerator"), notNullValue());
assertThat(provider.mocks.get("KeyPairGenerator").get("RSA"), notNullValue());
verify(mockPromise).resolve(SecurityLevel.SECURE_SOFTWARE.name());
}
@Test
public void testNodeValueListenerIfNotListening() {
int nodeId = 1;
createSimpleAnimatedViewWithOpacity(1000, 0d);
JavaOnlyArray frames = JavaOnlyArray.of(0d, 0.2d, 0.4d, 0.6d, 0.8d, 1d);
Callback animationCallback = mock(Callback.class);
AnimatedNodeValueListener valueListener = mock(AnimatedNodeValueListener.class);
mNativeAnimatedNodesManager.startListeningToAnimatedNodeValue(nodeId, valueListener);
mNativeAnimatedNodesManager.startAnimatingNode(
1,
nodeId,
JavaOnlyMap.of("type", "frames", "frames", frames, "toValue", 1d),
animationCallback);
mNativeAnimatedNodesManager.runUpdates(nextFrameTime());
verify(valueListener).onValueUpdate(eq(0d));
mNativeAnimatedNodesManager.stopListeningToAnimatedNodeValue(nodeId);
reset(valueListener);
mNativeAnimatedNodesManager.runUpdates(nextFrameTime());
verifyNoMoreInteractions(valueListener);
}
@Test
public void testUnderdampedSpringAnimation() {
performSpringAnimationTestWithConfig(
JavaOnlyMap.of(
"type",
"spring",
"stiffness",
230.2d,
"damping",
22d,
"mass",
1d,
"initialVelocity",
0d,
"toValue",
1d,
"restSpeedThreshold",
0.001d,
"restDisplacementThreshold",
0.001d,
"overshootClamping",
false
),
false
);
}
@Test
public void testCriticallyDampedSpringAnimation() {
performSpringAnimationTestWithConfig(
JavaOnlyMap.of(
"type",
"spring",
"stiffness",
1000d,
"damping",
500d,
"mass",
3.0d,
"initialVelocity",
0d,
"toValue",
1d,
"restSpeedThreshold",
0.001d,
"restDisplacementThreshold",
0.001d,
"overshootClamping",
false
),
true
);
}
@Test
public void parsesArrays() throws Exception {
JavaOnlyArray input = new JavaOnlyArray();
input.pushString("Hello");
input.pushInt(123);
input.pushDouble(123.456);
input.pushBoolean(true);
input.pushArray(new JavaOnlyArray());
input.pushMap(new JavaOnlyMap());
input.pushNull();
JSONArray result = new JSONParser().parse(input);
assertThat(result.length()).isEqualTo(6);
assertThat(result.get(0)).isEqualTo("Hello");
assertThat(result.get(1)).isEqualTo(123);
assertThat(result.get(2)).isEqualTo(123.456);
assertThat(result.get(3)).isEqualTo(true);
assertThat(result.getJSONArray(4).length()).isZero();
assertThat(result.getJSONObject(5).keys()).isEmpty();
}
@Test
public void givenCallback$getAllUserAttributes_whenQuery_thenShouldCallNativeApiAndInvokeCallback() {
// given
PowerMockito.mockStatic(Instabug.class);
PowerMockito.mockStatic(Arguments.class);
Callback callback = mock(Callback.class);
// when
HashMap<String, String> userAttributes = new HashMap<>();
userAttributes.put("email", "[email protected]");
PowerMockito.when(Arguments.createMap()).thenReturn(new JavaOnlyMap());
PowerMockito.when(Instabug.getAllUserAttributes()).thenReturn(userAttributes);
rnModule.getAllUserAttributes(callback);
// then
PowerMockito.verifyStatic(VerificationModeFactory.times(1));
Instabug.getAllUserAttributes();
WritableMap expectedMap = new JavaOnlyMap();
expectedMap.putString("email", "[email protected]");
verify(callback).invoke(expectedMap);
}
public void collectViewUpdates(JavaOnlyMap propsMap) {
for (Map.Entry<String, Integer> entry : mPropMapping.entrySet()) {
@Nullable AnimatedNode node = mNativeAnimatedNodesManager.getNodeById(entry.getValue());
if (node == null) {
throw new IllegalArgumentException("Mapped style node does not exists");
} else if (node instanceof TransformAnimatedNode) {
((TransformAnimatedNode) node).collectViewUpdates(propsMap);
} else if (node instanceof ValueAnimatedNode) {
propsMap.putDouble(entry.getKey(), ((ValueAnimatedNode) node).getValue());
} else {
throw new IllegalArgumentException("Unsupported type of node used in property node " +
node.getClass());
}
}
}
TrackingAnimatedNode(ReadableMap config, NativeAnimatedNodesManager nativeAnimatedNodesManager) {
mNativeAnimatedNodesManager = nativeAnimatedNodesManager;
mAnimationId = config.getInt("animationId");
mToValueNode = config.getInt("toValue");
mValueNode = config.getInt("value");
mAnimationConfig = JavaOnlyMap.deepClone(config.getMap("animationConfig"));
}
PropsAnimatedNode(ReadableMap config, NativeAnimatedNodesManager nativeAnimatedNodesManager, UIImplementation uiImplementation) {
ReadableMap props = config.getMap("props");
ReadableMapKeySetIterator iter = props.keySetIterator();
mPropNodeMapping = new HashMap<>();
while (iter.hasNextKey()) {
String propKey = iter.nextKey();
int nodeIndex = props.getInt(propKey);
mPropNodeMapping.put(propKey, nodeIndex);
}
mPropMap = new JavaOnlyMap();
mDiffMap = new ReactStylesDiffMap(mPropMap);
mNativeAnimatedNodesManager = nativeAnimatedNodesManager;
mUIImplementation = uiImplementation;
}
@Test
public void testPropsApplied() {
UIManagerModule uiManager = getUIManagerModule();
ReactRootView rootView = new ReactRootView(RuntimeEnvironment.application);
rootView.setLayoutParams(new ReactRootView.LayoutParams(100, 100));
int rootTag = uiManager.addRootView(rootView);
int textInputTag = rootTag + 1;
final String hintStr = "placeholder text";
uiManager.createView(
textInputTag,
ReactTextInputManager.REACT_CLASS,
rootTag,
JavaOnlyMap.of(
ViewProps.FONT_SIZE, 13.37, ViewProps.HEIGHT, 20.0, "placeholder", hintStr));
uiManager.manageChildren(
rootTag,
null,
null,
JavaOnlyArray.of(textInputTag),
JavaOnlyArray.of(0),
null);
uiManager.onBatchComplete();
executePendingChoreographerCallbacks();
EditText editText = (EditText) rootView.getChildAt(0);
assertThat(editText.getHint()).isEqualTo(hintStr);
assertThat(editText.getTextSize()).isEqualTo((float) Math.ceil(13.37));
assertThat(editText.getHeight()).isEqualTo(20);
}
@Test
public void testFontSizeApplied() {
UIManagerModule uiManager = getUIManagerModule();
ReactRootView rootView = createText(
uiManager,
JavaOnlyMap.of(ViewProps.FONT_SIZE, 21.0),
JavaOnlyMap.of(ReactRawTextShadowNode.PROP_TEXT, "test text"));
AbsoluteSizeSpan sizeSpan = getSingleSpan(
(TextView) rootView.getChildAt(0), AbsoluteSizeSpan.class);
assertThat(sizeSpan.getSize()).isEqualTo(21);
}
@Test
public void given$setOnSDKDismissedHandler_whenQuery_thenShouldSetNativeCallback() {
try {
// given
PowerMockito.mockStatic(BugReporting.class);
PowerMockito.mockStatic(Arguments.class);
PowerMockito.mockStatic(InstabugUtil.class);
// when
PowerMockito.when(Arguments.createMap()).thenReturn(new JavaOnlyMap());
PowerMockito.doAnswer(new Answer<Object>() {
@Override
public Object answer(InvocationOnMock invocation) {
((OnSdkDismissCallback) invocation.getArguments()[0])
.call(OnSdkDismissCallback.DismissType.CANCEL, OnSdkDismissCallback.ReportType.BUG);
return null;
}
}).when(BugReporting.class, "setOnDismissCallback", Matchers.anyObject());
bugReportingModule.setOnSDKDismissedHandler(null);
// then
WritableMap params = new JavaOnlyMap();
params.putString("dismissType", OnSdkDismissCallback.DismissType.CANCEL.toString());
params.putString("reportType", OnSdkDismissCallback.ReportType.BUG.toString());
PowerMockito.verifyStatic(VerificationModeFactory.times(1));
InstabugUtil.sendEvent(any(ReactApplicationContext.class), eq(Constants.IBG_POST_INVOCATION_HANDLER), eq(params));
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void testNumericBoldFontApplied() {
UIManagerModule uiManager = getUIManagerModule();
ReactRootView rootView = createText(
uiManager,
JavaOnlyMap.of(ViewProps.FONT_WEIGHT, "500"),
JavaOnlyMap.of(ReactRawTextShadowNode.PROP_TEXT, "test text"));
CustomStyleSpan customStyleSpan =
getSingleSpan((TextView) rootView.getChildAt(0), CustomStyleSpan.class);
assertThat(customStyleSpan.getWeight() & Typeface.BOLD).isNotZero();
assertThat(customStyleSpan.getStyle() & Typeface.ITALIC).isZero();
}
@Test
public void testItalicFontApplied() {
UIManagerModule uiManager = getUIManagerModule();
ReactRootView rootView = createText(
uiManager,
JavaOnlyMap.of(ViewProps.FONT_STYLE, "italic"),
JavaOnlyMap.of(ReactRawTextShadowNode.PROP_TEXT, "test text"));
CustomStyleSpan customStyleSpan =
getSingleSpan((TextView) rootView.getChildAt(0), CustomStyleSpan.class);
assertThat(customStyleSpan.getStyle() & Typeface.ITALIC).isNotZero();
assertThat(customStyleSpan.getWeight() & Typeface.BOLD).isZero();
}
@Test
public void testBoldItalicFontApplied() {
UIManagerModule uiManager = getUIManagerModule();
ReactRootView rootView = createText(
uiManager,
JavaOnlyMap.of(ViewProps.FONT_WEIGHT, "bold", ViewProps.FONT_STYLE, "italic"),
JavaOnlyMap.of(ReactRawTextShadowNode.PROP_TEXT, "test text"));
CustomStyleSpan customStyleSpan =
getSingleSpan((TextView) rootView.getChildAt(0), CustomStyleSpan.class);
assertThat(customStyleSpan.getStyle() & Typeface.ITALIC).isNotZero();
assertThat(customStyleSpan.getWeight() & Typeface.BOLD).isNotZero();
}
@Test
public void testNormalFontWeightApplied() {
UIManagerModule uiManager = getUIManagerModule();
ReactRootView rootView = createText(
uiManager,
JavaOnlyMap.of(ViewProps.FONT_WEIGHT, "normal"),
JavaOnlyMap.of(ReactRawTextShadowNode.PROP_TEXT, "test text"));
CustomStyleSpan customStyleSpan =
getSingleSpan((TextView) rootView.getChildAt(0), CustomStyleSpan.class);
assertThat(customStyleSpan.getWeight() & Typeface.BOLD).isZero();
}
@Test
public void testNumericNormalFontWeightApplied() {
UIManagerModule uiManager = getUIManagerModule();
ReactRootView rootView = createText(
uiManager,
JavaOnlyMap.of(ViewProps.FONT_WEIGHT, "200"),
JavaOnlyMap.of(ReactRawTextShadowNode.PROP_TEXT, "test text"));
CustomStyleSpan customStyleSpan =
getSingleSpan((TextView) rootView.getChildAt(0), CustomStyleSpan.class);
assertThat(customStyleSpan.getWeight() & Typeface.BOLD).isZero();
}
@Test
public void testNormalFontStyleApplied() {
UIManagerModule uiManager = getUIManagerModule();
ReactRootView rootView = createText(
uiManager,
JavaOnlyMap.of(ViewProps.FONT_STYLE, "normal"),
JavaOnlyMap.of(ReactRawTextShadowNode.PROP_TEXT, "test text"));
CustomStyleSpan customStyleSpan =
getSingleSpan((TextView) rootView.getChildAt(0), CustomStyleSpan.class);
assertThat(customStyleSpan.getStyle() & Typeface.ITALIC).isZero();
}