Skip to content

Commit

Permalink
Adding support for resource-id.
Browse files Browse the repository at this point in the history
* This closes facebook#9777.
  • Loading branch information
jsdevel committed Sep 21, 2016
1 parent 33c3d5d commit 51019b7
Show file tree
Hide file tree
Showing 9 changed files with 239 additions and 17 deletions.
29 changes: 29 additions & 0 deletions Libraries/Components/View/View.js
Original file line number Diff line number Diff line change
Expand Up @@ -258,6 +258,35 @@ const View = React.createClass({
* Used to locate this view in end-to-end tests.
*
* > This disables the 'layout-only view removal' optimization for this view!
*
* ### Support for resource-id on Android
*
* By default this value is passed to the underlying View's
* [setTag](https://developer.android.com/reference/android/view/View.html#setTag(java.lang.Object))
* method on android. Very few end to end testing frameworks support looking up
* a View by tag, let alone `uiautomatorviewer` which only supports `resource-id`, `text`, and `XPath`.
*
* While `react-native` does _not_ utilize XML based layouts for android Views it
* is still possible to add [android:id](https://developer.android.com/reference/android/view/View.html#attr_android:id)
* to the underlying View in order to support
* [findViewById](https://developer.android.com/reference/android/app/Activity.html#findViewById(int)).
*
* This is achieved by:
*
* 1. Defining a resource id in your android project's `res` folder (typically at
* `./android/app/src/main/res/values/ids.xml`.
*
* 1. Adding your resource ids to `ids.xml` E.G.
*
* ```xml
* <?xml version="1.0" encoding="utf-8"?>
* <resources>
* <item name="something" type="id"/>
* </resources>
*
* ```
* 1. Using the resource id as `testID` E.G. `<View testID="something">`.
*
*/
testID: PropTypes.string,

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@
import static com.facebook.react.bridge.ReactMarkerConstants.RUN_JS_BUNDLE_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.uimanager.BaseViewManager.getOriginalReactTag;
import static com.facebook.systrace.Systrace.TRACE_TAG_REACT_JAVA_BRIDGE;

/**
Expand Down Expand Up @@ -811,7 +812,7 @@ private void detachViewFromInstance(
CatalystInstance catalystInstance) {
UiThreadUtil.assertOnUiThread();
catalystInstance.getJSModule(AppRegistry.class)
.unmountApplicationComponentAtRootTag(rootView.getId());
.unmountApplicationComponentAtRootTag(getOriginalReactTag(rootView));
}

private void tearDownReactContext(ReactContext reactContext) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@
import android.view.ViewGroup;
import android.view.ViewParent;

import static com.facebook.react.uimanager.BaseViewManager.getOriginalReactTag;

/**
* This class coordinates JSResponder commands for {@link UIManagerModule}. It should be set as
* OnInterceptTouchEventListener for all newly created native views that implements
Expand Down Expand Up @@ -70,7 +72,7 @@ public boolean onInterceptTouchEvent(ViewGroup v, MotionEvent event) {
// Therefore since "UP" event is the last event in a gesture, we should just let it reach the
// original target that is a child view of {@param v}.
// http://developer.android.com/reference/android/view/ViewGroup.html#onInterceptTouchEvent(android.view.MotionEvent)
return v.getId() == currentJSResponder;
return getOriginalReactTag(v) == currentJSResponder;
}
return false;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,11 @@
import android.graphics.Color;
import android.os.Build;
import android.view.View;
import android.view.ViewGroup;

import com.facebook.react.bridge.ReadableArray;
import com.facebook.react.common.annotations.VisibleForTesting;
import com.facebook.react.uimanager.annotations.ReactProp;
import java.util.concurrent.ConcurrentHashMap;

/**
* Base class that should be suitable for the majority of subclasses of {@link ViewManager}.
Expand All @@ -35,6 +36,9 @@ public abstract class BaseViewManager<T extends View, C extends LayoutShadowNode
private static final String PROP_TRANSLATE_X = "translateX";
private static final String PROP_TRANSLATE_Y = "translateY";

private static final ConcurrentHashMap<String, Integer> TEST_IDS = new ConcurrentHashMap<>();
private static final ConcurrentHashMap<Integer, Integer> ORIGINAL_REACT_TAGS = new ConcurrentHashMap<>();

/**
* Used to locate views in end-to-end (UI) tests.
*/
Expand Down Expand Up @@ -84,6 +88,14 @@ public void setRenderToHardwareTexture(T view, boolean useHWTexture) {

@ReactProp(name = PROP_TEST_ID)
public void setTestId(T view, String testId) {
if (!TEST_IDS.containsKey(testId)) {
TEST_IDS.put(testId, view.getResources().getIdentifier(testId, "id", view.getContext().getPackageName()));
}
int mappedTestId = TEST_IDS.get(testId);
if (mappedTestId != 0) {
ORIGINAL_REACT_TAGS.put(System.identityHashCode(view), view.getId());
view.setId(mappedTestId);
}
view.setTag(testId);
}

Expand Down Expand Up @@ -153,6 +165,28 @@ public void setAccessibilityLiveRegion(T view, String liveRegion) {
}
}

/**
* Returns the tag originally generated by the JS when the view was created prior to
* it being potentially overwritten by {@link #setTestId}.
*
* @param view
* @param <T>
* @return
*/
public static <T extends View> int getOriginalReactTag(T view) {
Integer idFromJs = ORIGINAL_REACT_TAGS.get(System.identityHashCode(view));
return idFromJs != null ? idFromJs.intValue() : view.getId();
}

/**
* Used internally to clear the state of test ids.
*/
@VisibleForTesting
static void resetTestState() {
ORIGINAL_REACT_TAGS.clear();
TEST_IDS.clear();
}

private static void setTransformProperty(View view, ReadableArray transforms) {
TransformHelper.processTransform(transforms, sTransformDecompositionArray);
MatrixMathHelper.decomposeMatrix(sTransformDecompositionArray, sMatrixDecompositionContext);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@
import javax.annotation.Nullable;
import javax.annotation.concurrent.NotThreadSafe;

import static com.facebook.react.uimanager.BaseViewManager.getOriginalReactTag;

/**
* Delegate of {@link UIManagerModule} that owns the native view hierarchy and mapping between
* native view names used in JS and corresponding instances of {@link ViewManager}. The
Expand Down Expand Up @@ -212,9 +214,10 @@ public void createView(
mTagsToViews.put(tag, view);
mTagsToViewManagers.put(tag, viewManager);

// Use android View id field to store React tag. This is possible since we don't inflate
// React views from layout xmls. Thus it is easier to just reuse that field instead of
// creating another (potentially much more expensive) mapping from view to React tag
// Use android View id field to store React tag. Because testID will override this value
// (see {@link BaseViewManager#setTestId}) it is necessary to use
// {@link BaseViewManaget#getOriginalReactTag} whenever this original value is needed
// e.g. when communicating with the Shadow DOM or with JS about a particular node.
view.setId(tag);
if (initialProps != null) {
viewManager.updateProperties(view, initialProps);
Expand Down Expand Up @@ -358,7 +361,7 @@ public void manageChildren(

if (mLayoutAnimationEnabled &&
mLayoutAnimator.shouldAnimateLayout(viewToRemove) &&
arrayContains(tagsToDelete, viewToRemove.getId())) {
arrayContains(tagsToDelete, getOriginalReactTag(viewToRemove))) {
// The view will be removed and dropped by the 'delete' layout animation
// instead, so do nothing
} else {
Expand Down Expand Up @@ -512,24 +515,25 @@ protected final void addRootViewGroup(
*/
protected void dropView(View view) {
UiThreadUtil.assertOnUiThread();
if (!mRootTags.get(view.getId())) {
int originalReactTag = getOriginalReactTag(view);
if (!mRootTags.get(originalReactTag)) {
// For non-root views we notify viewmanager with {@link ViewManager#onDropInstance}
resolveViewManager(view.getId()).onDropViewInstance(view);
resolveViewManager(originalReactTag).onDropViewInstance(view);
}
ViewManager viewManager = mTagsToViewManagers.get(view.getId());
ViewManager viewManager = mTagsToViewManagers.get(originalReactTag);
if (view instanceof ViewGroup && viewManager instanceof ViewGroupManager) {
ViewGroup viewGroup = (ViewGroup) view;
ViewGroupManager viewGroupManager = (ViewGroupManager) viewManager;
for (int i = viewGroupManager.getChildCount(viewGroup) - 1; i >= 0; i--) {
View child = viewGroupManager.getChildAt(viewGroup, i);
if (mTagsToViews.get(child.getId()) != null) {
if (mTagsToViews.get(getOriginalReactTag(child)) != null) {
dropView(child);
}
}
viewGroupManager.removeAllViews(viewGroup);
}
mTagsToViews.remove(view.getId());
mTagsToViewManagers.remove(view.getId());
mTagsToViews.remove(originalReactTag);
mTagsToViewManagers.remove(originalReactTag);
}

public void removeRootView(int rootViewTag) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@
import com.facebook.react.bridge.UiThreadUtil;
import com.facebook.react.touch.ReactHitSlopView;

import static com.facebook.react.uimanager.BaseViewManager.getOriginalReactTag;

/**
* Class responsible for identifying which react view should handle a given {@link MotionEvent}.
* It uses the event coordinates to traverse the view hierarchy and return a suitable view.
Expand Down Expand Up @@ -87,7 +89,7 @@ public static int findTargetTagAndCoordinatesForTouch(
float[] viewCoords,
@Nullable int[] nativeViewTag) {
UiThreadUtil.assertOnUiThread();
int targetTag = viewGroup.getId();
int targetTag = getOriginalReactTag(viewGroup);
// Store eventCoords in array so that they are modified to be relative to the targetView found.
viewCoords[0] = eventX;
viewCoords[1] = eventY;
Expand Down Expand Up @@ -224,7 +226,7 @@ private static boolean isTransformedTouchPointInView(
// ViewGroup).
if (view instanceof ReactCompoundView) {
int reactTag = ((ReactCompoundView)view).reactTagForTouch(eventCoords[0], eventCoords[1]);
if (reactTag != view.getId()) {
if (reactTag != getOriginalReactTag(view)) {
// make sure we exclude the View itself because of the PointerEvents.BOX_NONE
return view;
}
Expand Down Expand Up @@ -256,7 +258,7 @@ private static int getTouchTargetForView(View targetView, float eventX, float ev
// {@link #findTouchTargetView()}.
return ((ReactCompoundView) targetView).reactTagForTouch(eventX, eventY);
}
return targetView.getId();
return getOriginalReactTag(targetView);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@

package com.facebook.react.uimanager.events;

import android.view.View;

import com.facebook.react.common.SystemClock;

/**
Expand Down Expand Up @@ -44,6 +46,11 @@ protected void init(int viewTag) {
}

/**
* TODO: Determine if this can be affected by testID. Specifically: When an event is dispatched
* to JS does the bridge need the Id or the tag? If the tag is needed, then
* {@link com.facebook.react.uimanager.BaseViewManager#getOriginalReactTag(View)}
* will be needed whenever an event is created.
*
* @return the view id for the view that generated this event
*/
public final int getViewTag() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@
import com.facebook.react.uimanager.ViewDefaults;
import com.facebook.react.views.view.ReactViewBackgroundDrawable;

import static com.facebook.react.uimanager.BaseViewManager.getOriginalReactTag;

public class ReactTextView extends TextView implements ReactCompoundView {

private static final ViewGroup.LayoutParams EMPTY_LAYOUT_PARAMS =
Expand Down Expand Up @@ -74,7 +76,7 @@ public void setText(ReactTextUpdate update) {
@Override
public int reactTagForTouch(float touchX, float touchY) {
Spanned text = (Spanned) getText();
int target = getId();
int target = getOriginalReactTag(this);

int x = (int) touchX;
int y = (int) touchY;
Expand Down
Loading

0 comments on commit 51019b7

Please sign in to comment.