com.facebook.litho.LithoView Java Examples

The following examples show how to use com.facebook.litho.LithoView. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: LithoViewSubComponentDeepExtractor.java    From litho with Apache License 2.0 6 votes vote down vote up
@Override
public List<InspectableComponent> extract(LithoView lithoView) {
  final List<InspectableComponent> res = new LinkedList<>();
  final Stack<InspectableComponent> stack = new Stack<>();

  final InspectableComponent rootInstance = InspectableComponent.getRootInstance(lithoView);
  if (rootInstance == null) {
    Preconditions.checkState(
        ComponentsConfiguration.IS_INTERNAL_BUILD,
        "Please ensure that ComponentsConfiguration.IS_INTERNAL_BUILD is enabled");
    throw new IllegalStateException("Component rendered to <null>");
  }
  stack.add(rootInstance);

  while (!stack.isEmpty()) {
    final InspectableComponent inspectableComponent = stack.pop();
    res.add(inspectableComponent);

    for (InspectableComponent child : inspectableComponent.getChildComponents()) {
      stack.push(child);
    }
  }

  return res;
}
 
Example #2
Source File: EventTriggerTest.java    From litho with Apache License 2.0 6 votes vote down vote up
@Test
public void testCanTriggerEvent() {
  Handle handle = new Handle();
  ComponentWithTrigger component =
      ComponentWithTrigger.create(mComponentContext).handle(handle).uniqueString("A").build();

  LithoView lithoView = ComponentTestHelper.mountComponent(mComponentContext, component);

  // The EventTriggers have been correctly applied to lithoView's ComponentTree
  // (EventTriggersContainer),
  // but this hasn't been applied to the ComponentTree inside mComponentContext.
  mComponentContext =
      ComponentContext.withComponentScope(
          ComponentContext.withComponentTree(
              lithoView.getComponentContext(), lithoView.getComponentTree()),
          component);

  assertThat(ComponentWithTrigger.testTriggerMethod(mComponentContext, handle)).isEqualTo("A");
}
 
Example #3
Source File: RecyclerBinder.java    From litho with Apache License 2.0 6 votes vote down vote up
@Override
public BaseViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
  final ViewCreator viewCreator = mRenderInfoViewCreatorController.getViewCreator(viewType);

  if (viewCreator != null) {
    final View view = viewCreator.createView(mComponentContext.getAndroidContext(), parent);
    return new BaseViewHolder(view, false);
  } else {
    final LithoView lithoView =
        mLithoViewFactory == null
            ? new LithoView(mComponentContext, null)
            : mLithoViewFactory.createLithoView(mComponentContext);

    return new BaseViewHolder(lithoView, true);
  }
}
 
Example #4
Source File: RecyclerBinder.java    From litho with Apache License 2.0 6 votes vote down vote up
@Override
public void onViewRecycled(BaseViewHolder holder) {
  if (holder.isLithoViewType) {
    final LithoView lithoView = (LithoView) holder.itemView;
    lithoView.unmountAllItems();
    lithoView.setComponentTree(null);
    lithoView.setInvalidStateLogParamsList(null);
    lithoView.resetMountStartupLoggingInfo();
  } else {
    final ViewBinder viewBinder = holder.viewBinder;
    if (viewBinder != null) {
      viewBinder.unbind(holder.itemView);
      holder.viewBinder = null;
    }
  }
}
 
Example #5
Source File: LithoAttributePlugin.java    From screenshot-tests-for-android with Apache License 2.0 6 votes vote down vote up
@Override
public void putAttributes(JSONObject node, Object obj, Point offset) throws JSONException {
  final DebugComponent debugComponent;
  if (obj instanceof LithoView) {
    ((LithoView) obj).rebind();
    debugComponent = DebugComponent.getRootInstance((LithoView) obj);
    if (debugComponent == null) {
      return;
    }
  } else {
    debugComponent = (DebugComponent) obj;

    // Since we're dealing with a pure component, we cant rely on the default required
    // attributes to be added, so we add them here
    Rect bounds = debugComponent.getBoundsInLithoView();
    putRequired(
        node,
        debugComponent.getComponent().getClass().getName(),
        offset.x + bounds.left,
        offset.y + bounds.top,
        bounds.width(),
        bounds.height());
  }
}
 
Example #6
Source File: RecyclerCollectionComponentSpecTest.java    From litho with Apache License 2.0 6 votes vote down vote up
@Test
public void testNestedIncrementalMountNormal() {
  LithoView view =
      ComponentTestHelper.mountComponent(
          mComponentContext,
          RecyclerCollectionComponent.create(mComponentContext)
              .section(
                  SingleComponentSection.create(new SectionContext(mComponentContext))
                      .component(
                          Row.create(mComponentContext)
                              .viewTag("rv_row")
                              .heightDip(100)
                              .widthDip(100))
                      .build())
              .build(),
          true,
          true);

  final LithoView childView = (LithoView) findViewWithTag(view, "rv_row");
  assertThat(childView).isNotNull();
  assertThat(childView.getComponentTree().isIncrementalMountEnabled()).isTrue();
}
 
Example #7
Source File: HorizontalScrollWithSnapActivity.java    From litho with Apache License 2.0 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);

  final ComponentContext componentContext = new ComponentContext(this);
  final LinearLayout container = new LinearLayout(this);
  container.setOrientation(LinearLayout.VERTICAL);
  final RecyclerCollectionEventsController eventsController =
      new RecyclerCollectionEventsController();
  container.addView(
      LithoView.create(
          this,
          HorizontalScrollWithSnapComponent.create(componentContext)
              .colors(colors)
              .eventsController(eventsController)
              .build()));
  container.addView(
      LithoView.create(
          this,
          HorizontalScrollScrollerComponent.create(componentContext)
              .colors(colors)
              .eventsController(eventsController)
              .build()));
  setContentView(container);
}
 
Example #8
Source File: StateResettingActivity.java    From litho with Apache License 2.0 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);

  mData = getData();
  mComponentContext = new ComponentContext(this);

  mLithoView =
      LithoView.create(
          this,
          StateResettingRootComponent.create(mComponentContext)
              .dataModels(mData)
              .showHeader(false)
              .build());

  setContentView(mLithoView);

  fetchHeader();
}
 
Example #9
Source File: LithoHierarchyPlugin.java    From screenshot-tests-for-android with Apache License 2.0 6 votes vote down vote up
@Override
public void putHierarchy(LayoutHierarchyDumper dumper, JSONObject root, Object obj, Point offset)
    throws JSONException {
  if (!accept(obj)) {
    return;
  }

  if (obj instanceof LithoView) {
    LithoView lithoView = (LithoView) obj;
    DebugComponent debugComponent = DebugComponent.getRootInstance(lithoView);
    if (debugComponent == null) {
      return;
    }
    final int offsetLeft = LayoutHierarchyDumper.getViewLeft(lithoView);
    final int offsetTop = LayoutHierarchyDumper.getViewTop(lithoView);
    offset.offset(offsetLeft, offsetTop);
    dumpHierarchy(dumper, root, debugComponent, offset);
    offset.offset(-offsetLeft, -offsetTop);
  } else {
    dumpHierarchy(dumper, root, (DebugComponent) obj, offset);
  }
}
 
Example #10
Source File: PropUpdatingActivity.java    From litho with Apache License 2.0 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);

  mComponentContext = new ComponentContext(this);

  mDataModels = getData(5);

  mLithoView =
      LithoView.create(
          this,
          SelectedItemRootComponent.create(mComponentContext)
              .dataModels(mDataModels)
              .selectedItem(0)
              .build());

  setContentView(mLithoView);

  fetchData();
}
 
Example #11
Source File: ItemsRerenderingActivity.java    From litho with Apache License 2.0 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);

  mComponentContext = new ComponentContext(this);

  mLithoView =
      LithoView.create(
          this,
          ItemsRerenderingRootComponent.create(mComponentContext)
              .dataModels(getData(15))
              .build());

  setContentView(mLithoView);

  fetchData();
}
 
Example #12
Source File: LithoViewSubComponentExtractor.java    From litho with Apache License 2.0 6 votes vote down vote up
public static Condition<? super LithoView> subComponentWith(
    final Condition<InspectableComponent> inner) {
  return new Condition<LithoView>() {
    @Override
    public boolean matches(LithoView value) {
      as("sub component with <%s>", inner);
      for (InspectableComponent component : subComponents().extract(value)) {
        if (inner.matches(component)) {
          return true;
        }
      }

      return false;
    }
  };
}
 
Example #13
Source File: RecyclerCollectionComponentSpecTest.java    From litho with Apache License 2.0 6 votes vote down vote up
@Test
public void testNestedIncrementalMountDisabled() {
  LithoView view =
      ComponentTestHelper.mountComponent(
          mComponentContext,
          RecyclerCollectionComponent.create(mComponentContext)
              .section(
                  SingleComponentSection.create(new SectionContext(mComponentContext))
                      .component(
                          Row.create(mComponentContext)
                              .viewTag("rv_row")
                              .heightDip(100)
                              .widthDip(100))
                      .build())
              .build(),
          false,
          false);

  final LithoView childView = (LithoView) findViewWithTag(view, "rv_row");
  assertThat(childView).isNotNull();
  assertThat(childView.getComponentTree().isIncrementalMountEnabled()).isFalse();
}
 
Example #14
Source File: RecyclerCollectionComponentSpecTest.java    From litho with Apache License 2.0 6 votes vote down vote up
@Test
public void testEmpty() throws Exception {
  LithoView view =
      StateUpdatesTestHelper.getViewAfterStateUpdate(
          mComponentContext,
          mRecyclerCollectionComponent,
          new StateUpdatesTestHelper.StateUpdater() {
            @Override
            public void performStateUpdate(ComponentContext context) {
              RecyclerCollectionComponent.updateLoadingState(context, EMPTY);
            }
          });

  ViewTreeAssert.assertThat(ViewTree.of(view))
      .doesNotHaveVisibleText("loading")
      .hasVisibleText("content")
      .hasVisibleText("empty")
      .doesNotHaveVisibleText("error");
}
 
Example #15
Source File: StateUpdatesTestHelper.java    From litho with Apache License 2.0 6 votes vote down vote up
/**
 * Call a state update as specified in {@link StateUpdater#performStateUpdate(ComponentContext)}
 * on the component and return the updated view with the option to incrementally mount.
 *
 * @param context context
 * @param component the component to update
 * @param stateUpdater implementation of {@link StateUpdater} that triggers the state update
 * @param layoutThreadShadowLooper shadow looper to post messages to the main thread
 * @param incrementalMountEnabled whether or not to enable incremental mount for the component
 * @return the updated LithoView after the state update was applied
 */
public static LithoView getViewAfterStateUpdate(
    ComponentContext context,
    Component component,
    StateUpdater stateUpdater,
    ShadowLooper layoutThreadShadowLooper,
    boolean incrementalMountEnabled,
    boolean visibilityProcessingEnabled) {
  return getViewAfterStateUpdate(
      context,
      component,
      stateUpdater,
      new ShadowLooper[] {layoutThreadShadowLooper},
      incrementalMountEnabled,
      visibilityProcessingEnabled);
}
 
Example #16
Source File: TextSpecTest.java    From litho with Apache License 2.0 6 votes vote down vote up
@Test
public void testTouchOffsetChangeHandlerFired() {
  final boolean[] eventFired = new boolean[] {false};
  EventHandler<TextOffsetOnTouchEvent> eventHandler =
      EventHandlerTestHelper.createMockEventHandler(
          TextOffsetOnTouchEvent.class,
          new EventHandlerTestHelper.MockEventHandler<TextOffsetOnTouchEvent, Void>() {
            @Override
            public Void handleEvent(TextOffsetOnTouchEvent event) {
              eventFired[0] = true;
              return null;
            }
          });

  LithoView lithoView =
      ComponentTestHelper.mountComponent(
          mContext,
          Text.create(mContext).text("Some text").textOffsetOnTouchHandler(eventHandler).build());
  TextDrawable textDrawable = (TextDrawable) (lithoView.getDrawables().get(0));
  MotionEvent motionEvent = MotionEvent.obtain(0, 0, MotionEvent.ACTION_DOWN, 0, 0, 0);
  boolean handled = textDrawable.onTouchEvent(motionEvent, lithoView);
  // We don't consume touch events from TextTouchOffsetChange event
  assertThat(handled).isFalse();
  assertThat(eventFired[0]).isTrue();
}
 
Example #17
Source File: StickyHeaderControllerTest.java    From litho with Apache License 2.0 6 votes vote down vote up
@Test
public void testTranslateRecyclerViewChild() {
  SectionsRecyclerView recycler = mock(SectionsRecyclerView.class);
  RecyclerView recyclerView = mock(RecyclerView.class);
  when(recycler.getRecyclerView()).thenReturn(recyclerView);
  when(recyclerView.getLayoutManager()).thenReturn(mock(RecyclerView.LayoutManager.class));
  mStickyHeaderController.init(recycler);

  when(mHasStickyHeader.findFirstVisibleItemPosition()).thenReturn(2);
  when(mHasStickyHeader.isSticky(2)).thenReturn(true);

  ComponentTree componentTree = mock(ComponentTree.class);
  when(mHasStickyHeader.getComponentForStickyHeaderAt(2)).thenReturn(componentTree);
  LithoView lithoView = mock(LithoView.class);
  when(componentTree.getLithoView()).thenReturn(lithoView);

  mStickyHeaderController.onScrolled(null, 0, 0);

  verify(lithoView).setTranslationY(anyFloat());
  verify(recycler, times(2)).hideStickyHeader();
}
 
Example #18
Source File: ScrollingToBottomActivity.java    From litho with Apache License 2.0 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);

  mComponentContext = new ComponentContext(this);
  mFeedData = getData(15, 15);

  mLithoView =
      LithoView.create(
          this,
          DelayedLoadingComponent.create(mComponentContext)
              .headerDataModels(null)
              .feedDataModels(mFeedData)
              .build());

  setContentView(mLithoView);

  fetchData();
}
 
Example #19
Source File: RecyclerCollectionComponentSpecTest.java    From litho with Apache License 2.0 6 votes vote down vote up
@Test
public void testError() throws Exception {
  LithoView view =
      StateUpdatesTestHelper.getViewAfterStateUpdate(
          mComponentContext,
          mRecyclerCollectionComponent,
          new StateUpdatesTestHelper.StateUpdater() {
            @Override
            public void performStateUpdate(ComponentContext context) {
              RecyclerCollectionComponent.updateLoadingState(context, ERROR);
            }
          });

  ViewTreeAssert.assertThat(ViewTree.of(view))
      .doesNotHaveVisibleText("loading")
      .hasVisibleText("content")
      .doesNotHaveVisibleText("empty")
      .hasVisibleText("error");
}
 
Example #20
Source File: LithoViewSubComponentDeepExtractor.java    From litho with Apache License 2.0 6 votes vote down vote up
public static Condition<LithoView> deepSubComponentWith(
    final Condition<InspectableComponent> inner) {
  return new Condition<LithoView>() {
    @Override
    public boolean matches(LithoView lithoView) {
      as("deep sub component with <%s>", inner);
      for (InspectableComponent component : subComponentsDeeply().extract(lithoView)) {
        if (inner.matches(component)) {
          return true;
        }
      }

      return false;
    }
  };
}
 
Example #21
Source File: TextSpecTest.java    From litho with Apache License 2.0 5 votes vote down vote up
@Test
public void testTouchOffsetChangeHandlerNotFired() {
  final boolean[] eventFired = new boolean[] {false};
  EventHandler<TextOffsetOnTouchEvent> eventHandler =
      EventHandlerTestHelper.createMockEventHandler(
          TextOffsetOnTouchEvent.class,
          new EventHandlerTestHelper.MockEventHandler<TextOffsetOnTouchEvent, Void>() {
            @Override
            public Void handleEvent(TextOffsetOnTouchEvent event) {
              eventFired[0] = true;
              return null;
            }
          });

  LithoView lithoView =
      ComponentTestHelper.mountComponent(
          mContext,
          Text.create(mContext).text("Text2").textOffsetOnTouchHandler(eventHandler).build());

  TextDrawable textDrawable = (TextDrawable) (lithoView.getDrawables().get(0));

  MotionEvent actionUp = MotionEvent.obtain(0, 0, MotionEvent.ACTION_UP, 0, 0, 0);
  boolean handledActionUp = textDrawable.onTouchEvent(actionUp, lithoView);
  assertThat(handledActionUp).isFalse();
  assertThat(eventFired[0]).isFalse();

  MotionEvent actionDown = MotionEvent.obtain(0, 0, MotionEvent.ACTION_MOVE, 0, 0, 0);
  boolean handledActionMove = textDrawable.onTouchEvent(actionDown, lithoView);
  assertThat(handledActionMove).isFalse();
  assertThat(eventFired[0]).isFalse();
}
 
Example #22
Source File: ComponentQueriesTest.java    From litho with Apache License 2.0 5 votes vote down vote up
@Test
public void testTextOnComponent() {
  final LithoView view =
      ComponentTestHelper.mountComponent(mContext, Text.create(mContext).text("hello").build());

  assertThat(ComponentQueries.hasTextMatchingPredicate(view, Predicates.equalTo("hello")))
      .isTrue();
}
 
Example #23
Source File: ImageRowScreenshotTest.java    From screenshot-tests-for-android with Apache License 2.0 5 votes vote down vote up
@Test
public void testDefault() {
  Context targetContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
  LayoutInflater inflater = LayoutInflater.from(targetContext);
  LithoView view = (LithoView) inflater.inflate(R.layout.litho_view, null, false);

  view.setComponent(ImageRow.create(view.getComponentContext()).build());

  ViewHelpers.setupView(view).setExactWidthDp(300).layout();
  Screenshot.snap(view).record();
}
 
Example #24
Source File: AnimationCookBookActivity.java    From litho with Apache License 2.0 5 votes vote down vote up
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  final ComponentContext componentContext = new ComponentContext(this);
  Component component =
      RecyclerCollectionComponent.create(componentContext)
          .disablePTR(true)
          .section(
              AnimationCookBookListSection.create(new SectionContext(componentContext)).build())
          .build();
  LithoView lithoView = LithoView.create(this, component);
  setContentView(lithoView);
}
 
Example #25
Source File: SizeSpecMountWrapperComponentSpec.java    From litho with Apache License 2.0 5 votes vote down vote up
@UiThread
@OnMount
static void onMount(
    ComponentContext c,
    FrameLayout wrapperView,
    @State AtomicReference<ComponentTree> componentTreeRef) {
  ((LithoView) wrapperView.getChildAt(0)).setComponentTree(componentTreeRef.get());
}
 
Example #26
Source File: DynamicPropsActivity.java    From litho with Apache License 2.0 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);

  if (savedInstanceState == null) {
    mTimeValue = new DynamicValue<>(0L);
    mAlphaValue = new DynamicValue<>(0F);
  }

  setContentView(R.layout.activity_dynamic_props);

  mTimeLabel = findViewById(R.id.time);
  mAlphaLabel = findViewById(R.id.alpha);

  final LithoView lithoView = findViewById(R.id.lithoView);
  final ComponentContext c = new ComponentContext(this);
  final Component component =
      ClockComponent.create(c).time(mTimeValue).alpha(mAlphaValue).build();
  lithoView.setComponentTree(ComponentTree.create(c, component).build());

  mSeekBar = findViewById(R.id.seekBar);
  mSeekBar.setMax((int) DAY);
  mSeekBar.setOnSeekBarChangeListener(this);

  final SeekBar alphaSeekBar = findViewById(R.id.alphaSeekBar);
  alphaSeekBar.setMax(100);
  alphaSeekBar.setProgress(100);
  alphaSeekBar.setOnSeekBarChangeListener(this);

  reset(null);
  setAlpha(1F);
}
 
Example #27
Source File: AnimatedProperties.java    From litho with Apache License 2.0 5 votes vote down vote up
@Override
public float get(Object mountContent) {
  if (mountContent instanceof LithoView) {
    return ((LithoView) mountContent).getX();
  } else if (mountContent instanceof View) {
    return getPositionRelativeToLithoView((View) mountContent, true);
  } else if (mountContent instanceof Drawable) {
    final Drawable drawable = (Drawable) mountContent;
    float parentX = getPositionRelativeToLithoView(getHostView(drawable), true);
    return parentX + drawable.getBounds().left;
  } else {
    throw new UnsupportedOperationException(
        "Getting X from unsupported mount content: " + mountContent);
  }
}
 
Example #28
Source File: ErrorHandlingActivity.java    From litho with Apache License 2.0 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);

  // This feature is currently experimental and not enabled by default.
  ComponentsConfiguration.enableOnErrorHandling = true;

  setContentView(
      LithoView.create(
          this,
          ErrorRootComponent.create(new ComponentContext(this))
              .dataModels(Arrays.asList(DATA))
              .build()));
}
 
Example #29
Source File: SampleActivity.java    From litho with Apache License 2.0 5 votes vote down vote up
@Override
public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);

  final ComponentContext context = new ComponentContext(this);

  final Component component =
      RecyclerCollectionComponent.create(context)
          .disablePTR(true)
          .section(ListSection.create(new SectionContext(context)).build())
          .build();

  setContentView(LithoView.create(context, component));
}
 
Example #30
Source File: ExampleScreenshotTest.java    From screenshot-tests-for-android with Apache License 2.0 5 votes vote down vote up
@Test
public void testDefault() {
  Context targetContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
  LayoutInflater inflater = LayoutInflater.from(targetContext);
  LithoView view = (LithoView) inflater.inflate(R.layout.litho_view, null, false);

  view.setComponent(Example.create(view.getComponentContext()).build());

  ViewHelpers.setupView(view).setExactWidthDp(300).layout();
  Screenshot.snap(view).record();
}