com.facebook.litho.ComponentContext Java Examples

The following examples show how to use com.facebook.litho.ComponentContext. 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: 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 #2
Source File: VaryingRadiiBorderSpec.java    From litho with Apache License 2.0 6 votes vote down vote up
@OnCreateLayout
static Component onCreateLayout(ComponentContext c) {
  return Row.create(c)
      .child(Text.create(c).textSizeSp(20).text("This component has varying corner radii"))
      .border(
          Border.create(c)
              .widthDip(YogaEdge.ALL, 3)
              .color(YogaEdge.LEFT, Color.BLACK)
              .color(YogaEdge.TOP, NiceColor.GREEN)
              .color(YogaEdge.BOTTOM, NiceColor.BLUE)
              .color(YogaEdge.RIGHT, NiceColor.RED)
              .radiusDip(Corner.TOP_LEFT, 10)
              .radiusDip(Corner.TOP_RIGHT, 5)
              .radiusDip(Corner.BOTTOM_RIGHT, 20)
              .radiusDip(Corner.BOTTOM_LEFT, 30)
              .build())
      .build();
}
 
Example #3
Source File: RecyclerCollectionComponentSpecTest.java    From litho with Apache License 2.0 6 votes vote down vote up
@Test
public void rcc_insertMountSpecWorkingRangeTester_workingRangeIsRegisteredAndEntered() {
  final ComponentContext componentContext = mLithoViewRule.getContext();
  final List<LifecycleStep.StepInfo> info = new ArrayList<>();
  final Component component =
      MountSpecWorkingRangeTester.create(componentContext).steps(info).heightPx(100).build();
  final RecyclerCollectionComponent rcc =
      RecyclerCollectionComponent.create(componentContext)
          .recyclerConfiguration(ListRecyclerConfiguration.create().build())
          .section(
              SingleComponentSection.create(new SectionContext(componentContext))
                  .component(component)
                  .build())
          .build();
  mLithoViewRule
      .setRoot(rcc)
      .setSizeSpecs(makeMeasureSpec(100, EXACTLY), makeMeasureSpec(100, EXACTLY));

  mLithoViewRule.attachToWindow().measure().layout();

  assertThat(getSteps(info))
      .describedAs("Should register and enter working range in expected order")
      .containsExactly(LifecycleStep.ON_REGISTER_RANGES, LifecycleStep.ON_ENTERED_RANGE);
}
 
Example #4
Source File: HorizontalScrollRootComponentSpec.java    From litho with Apache License 2.0 6 votes vote down vote up
@OnCreateInitialState
static void createInitialState(
    ComponentContext c,
    StateValue<ImmutableList<Pair<String, Integer>>> items,
    StateValue<Integer> prependCounter,
    StateValue<Integer> appendCounter) {
  final List<Pair<String, Integer>> initialItems = new ArrayList<>();
  initialItems.add(new Pair<>("Coral", 0xFFFF7F50));
  initialItems.add(new Pair<>("Ivory", 0xFFFFFFF0));
  initialItems.add(new Pair<>("PeachPuff", 0xFFFFDAB9));
  initialItems.add(new Pair<>("LightPink", 0xFFFFB6C1));
  initialItems.add(new Pair<>("LavenderBlush", 0xFFFFF0F5));
  initialItems.add(new Pair<>("Gold", 0xFFFFD700));
  initialItems.add(new Pair<>("BlanchedAlmond", 0xFFFFEBCD));
  initialItems.add(new Pair<>("FloralWhite", 0xFFFFFAF0));
  initialItems.add(new Pair<>("Moccasin", 0xFFFFE4B5));
  initialItems.add(new Pair<>("LightYellow", 0xFFFFFFE0));
  items.set(new ImmutableList.Builder<Pair<String, Integer>>().addAll(initialItems).build());
  prependCounter.set(0);
  appendCounter.set(0);
}
 
Example #5
Source File: TestLayout.java    From litho with Apache License 2.0 6 votes vote down vote up
@Override
protected Transition onCreateTransition(ComponentContext c) {
  Transition _result;
  Diff<Integer> _state3Diff =
      new Diff<Integer>(
          mPreviousRenderData == null ? null : mPreviousRenderData.state3,
          mStateContainer.state3);
  _result =
      (Transition)
          TestLayoutSpec.onCreateTransition(
              (ComponentContext) c,
              (Object) prop3,
              (long) mStateContainer.state1,
              (Diff<Integer>) _state3Diff);
  return _result;
}
 
Example #6
Source File: HorizontalScrollSpec.java    From litho with Apache License 2.0 6 votes vote down vote up
@OnCreateInitialState
static void onCreateInitialState(
    ComponentContext c,
    StateValue<ScrollPosition> lastScrollPosition,
    StateValue<ComponentTree> childComponentTree,
    @Prop Component contentProps,
    @Prop(optional = true) int initialScrollPosition) {

  lastScrollPosition.set(new ScrollPosition(initialScrollPosition));
  childComponentTree.set(
      ComponentTree.create(
              new ComponentContext(
                  c.getAndroidContext(), c.getLogTag(), c.getLogger(), c.getTreePropsCopy()),
              contentProps)
          .incrementalMount(false)
          .build());
}
 
Example #7
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 #8
Source File: TestMount.java    From litho with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
protected void onLoadStyle(ComponentContext c) {
  Output<Boolean> prop2Tmp = new Output<>();
  Output<Object> prop3Tmp = new Output<>();
  TestMountSpec.onLoadStyle(
      (ComponentContext) c, (Output<Boolean>) prop2Tmp, (Output<Object>) prop3Tmp);
  if (prop2Tmp.get() != null) {
    prop2 = prop2Tmp.get();
  }
  if (prop3Tmp.get() != null) {
    prop3 = prop3Tmp.get();
  }
}
 
Example #9
Source File: StateUpdatesTestHelper.java    From litho with Apache License 2.0 5 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 loopers shadow loopers to post messages to the main thread, run in the same order they
 *     are specified
 * @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[] loopers,
    boolean incrementalMountEnabled,
    boolean visibilityProcessingEnabled) {
  // This is for working around component immutability, to be able to retrieve the updated
  // instance of the component.
  Whitebox.invokeMethod(component, "setKey", "bogusKeyForTest");
  final ComponentTree componentTree =
      ComponentTree.create(context, component)
          .incrementalMount(incrementalMountEnabled)
          .visibilityProcessing(visibilityProcessingEnabled)
          .layoutDiffing(false)
          .build();

  final LithoView lithoView = new LithoView(context);
  ComponentTestHelper.mountComponent(lithoView, componentTree);

  Whitebox.setInternalState(component, "mGlobalKey", "bogusKeyForTest");
  Whitebox.setInternalState(component, "mId", 457282882);

  Whitebox.setInternalState(context, "mComponentScope", component);
  Whitebox.setInternalState(context, "mComponentTree", componentTree);

  final LithoViewTestHelper.InternalNodeRef rootLayoutNode =
      LithoViewTestHelper.getRootLayoutRef(lithoView);

  stateUpdater.performStateUpdate(context);
  for (ShadowLooper looper : loopers) {
    looper.runToEndOfTasks();
  }

  LithoViewTestHelper.setRootLayoutRef(lithoView, rootLayoutNode);
  return ComponentTestHelper.mountComponent(lithoView, componentTree);
}
 
Example #10
Source File: SubComponentExtractor.java    From litho with Apache License 2.0 5 votes vote down vote up
/**
 * This combinator allows you to make an assertion on the number of sub-components directly spun
 * up by the component under test.
 *
 * @param c The ComponentContext used to create the tree.
 * @param matcher The Matcher that verifies the number of sub-components against a condition
 */
public static Condition<? super Component> numOfSubComponents(
    final ComponentContext c, final Matcher<Integer> matcher) {
  return new Condition<Component>() {
    @Override
    public boolean matches(Component component) {
      final int num = subComponents(c).extract(component).size();
      as("number of sub components %s but was %d", matcher.toString(), num);
      return matcher.matches(num);
    }
  };
}
 
Example #11
Source File: AllBorderSpec.java    From litho with Apache License 2.0 5 votes vote down vote up
@OnCreateLayout
static Component onCreateLayout(ComponentContext c) {
  return Row.create(c)
      .child(
          Text.create(c)
              .textSizeSp(20)
              .text("This component has all borders specified to the same color + width"))
      .border(
          Border.create(c).color(YogaEdge.ALL, NiceColor.BLUE).widthDip(YogaEdge.ALL, 5).build())
      .build();
}
 
Example #12
Source File: TransitionEndCallbackTestComponentSpec.java    From litho with Apache License 2.0 5 votes vote down vote up
private static Component getDisappearComponent(ComponentContext c, boolean state) {
  return Column.create(c)
      .child(Row.create(c).heightDip(50).widthDip(50).backgroundColor(Color.YELLOW))
      .child(
          !state
              ? Row.create(c)
                  .heightDip(50)
                  .widthDip(50)
                  .backgroundColor(Color.RED)
                  .transitionKey(TRANSITION_KEY)
                  .key(TRANSITION_KEY)
              : null)
      .build();
}
 
Example #13
Source File: SharedElementsActivity.java    From litho with Apache License 2.0 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);

  final ComponentContext c = new ComponentContext(this);
  LithoView lithoView = LithoView.create(this, SharedElementsComponent.create(c).build());
  setContentView(lithoView);
}
 
Example #14
Source File: TitleComponentSpec.java    From litho with Apache License 2.0 5 votes vote down vote up
@OnCreateLayout
static Component onCreateLayout(ComponentContext c, @Prop(resType = STRING) String title) {
  return Text.create(c)
      .text(title)
      .textStyle(BOLD)
      .textSizeDip(24)
      .backgroundColor(0xDDFFFFFF)
      .positionType(YogaPositionType.ABSOLUTE)
      .positionDip(YogaEdge.BOTTOM, 4)
      .positionDip(YogaEdge.LEFT, 4)
      .paddingDip(YogaEdge.HORIZONTAL, 6)
      .build();
}
 
Example #15
Source File: BounceExampleComponentSpec.java    From litho with Apache License 2.0 5 votes vote down vote up
@OnEvent(ClickEvent.class)
static void onClick(
    ComponentContext c,
    @State AtomicReference<Animator> animatorRef,
    @State DynamicValue<Float> translationY) {
  Animator oldAnimator = animatorRef.get();
  if (oldAnimator != null) {
    oldAnimator.cancel();
  }

  final Animator newAnimator = createBounceAnimator(c, translationY);
  animatorRef.set(newAnimator);
  newAnimator.start();
}
 
Example #16
Source File: HorizontalScrollScrollerComponentSpec.java    From litho with Apache License 2.0 5 votes vote down vote up
@OnEvent(ItemSelectedEvent.class)
static void onScrollToPositionSelected(
    ComponentContext c,
    @FromEvent String newSelection,
    @Prop RecyclerCollectionEventsController eventsController) {
  eventsController.requestScrollToPositionWithSnap(Integer.parseInt(newSelection));
}
 
Example #17
Source File: FeedItemComponentSpecSubComponentTest.java    From litho with Apache License 2.0 5 votes vote down vote up
@Test
public void subComponentWithMatcher() {
  final ComponentContext c = mComponentsRule.getContext();
  final Component component =
      makeComponentWithTextInSubcomponent(
          "Long Text That We Don't Want To Match In Its Entirety");

  // We can pass in any of the default hamcrest matchers here.
  assertThat(c, component)
      .extractingSubComponentAt(0)
      .has(
          subComponentWith(
              c, TestFooterComponent.matcher(c).text(containsString("Want To Match")).build()));
}
 
Example #18
Source File: BasicLayoutSpec.java    From litho with Apache License 2.0 5 votes vote down vote up
@OnCreateLayout
static Component onCreateLayout(
    ComponentContext context,
    @Prop String myStringProp,
    @Prop(resType = ResType.COLOR) int myRequiredColorProp,
    @Prop(resType = ResType.DIMEN_SIZE) float myDimenSizeProp,
    @Prop Component child) {
  return null;
}
 
Example #19
Source File: AnimationTest.java    From litho with Apache License 2.0 5 votes vote down vote up
@Test
public void
    animationTransitionsExtension_reUsingLithoViewWithDifferentComponentTrees_shouldNotCrash() {
  final boolean useExtensionsWithMountDelegate =
      ComponentsConfiguration.useExtensionsWithMountDelegate;
  ComponentsConfiguration.useExtensionsWithMountDelegate = true;

  ComponentContext componentContext = new ComponentContext(RuntimeEnvironment.application);

  mLithoViewRule.setRoot(getNonAnimatingComponent());
  // We measure and layout this non animating component to initialize the transition extension.
  mLithoViewRule.measure().layout();

  // We need an other litho view where we are going to measure and layout an other similar tree
  // (the real difference here is that the root components are not animating)
  LithoView lithoView = new LithoView(componentContext);
  ComponentTree nonAnimatingComponentTree = ComponentTree.create(componentContext).build();
  nonAnimatingComponentTree.setRoot(getNonAnimatingComponent());
  lithoView.setComponentTree(nonAnimatingComponentTree);
  lithoView.measure(LithoViewRule.DEFAULT_WIDTH_SPEC, LithoViewRule.DEFAULT_HEIGHT_SPEC);
  lithoView.layout(0, 0, lithoView.getMeasuredWidth(), lithoView.getMeasuredHeight());

  // Now we need a new component tree that will hold a component tree that holds an animating root
  // component.
  ComponentTree animatingComponentTree = ComponentTree.create(componentContext).build();
  animatingComponentTree.setRoot(getAnimatingXPropertyComponent());

  mLithoViewRule.useComponentTree(animatingComponentTree);
  // We measure this component tree so we initialize the mRootTransition in the extension, but we
  // end up not running a layout here.
  mLithoViewRule.measure();

  // Finally we set a new animating component tree to the initial litho view and run measure and
  // layout.
  mLithoViewRule.useComponentTree(nonAnimatingComponentTree);
  mLithoViewRule.measure().layout();
  // Should not crash.
  ComponentsConfiguration.useExtensionsWithMountDelegate = useExtensionsWithMountDelegate;
}
 
Example #20
Source File: TestViewComponent.java    From litho with Apache License 2.0 5 votes vote down vote up
@Override
protected void onMeasure(
    ComponentContext c, ComponentLayout layout, int widthSpec, int heightSpec, Size size) {
  int width = SizeSpec.getSize(widthSpec);
  int height = SizeSpec.getSize(heightSpec);

  size.height = height;
  size.width = width;

  onMeasureCalled();
}
 
Example #21
Source File: ComponentHostMatchersTest.java    From litho with Apache License 2.0 5 votes vote down vote up
@UiThreadTest
@Before
public void before() throws Throwable {
  final ComponentContext mComponentContext =
      new ComponentContext(InstrumentationRegistry.getTargetContext());
  final Component mTextComponent =
      MyComponent.create(mComponentContext).text("foobar").customViewTag("zoidberg").build();
  final ComponentTree tree = ComponentTree.create(mComponentContext, mTextComponent).build();
  mView = new LithoView(mComponentContext);
  mView.setComponentTree(tree);
  ViewHelpers.setupView(mView).setExactWidthPx(200).setExactHeightPx(100).layout();
}
 
Example #22
Source File: FrescoVitoImage2Spec.java    From fresco with MIT License 5 votes vote down vote up
@OnMeasure
static void onMeasure(
    ComponentContext c,
    ComponentLayout layout,
    int widthSpec,
    int heightSpec,
    Size size,
    @Prop(optional = true, resType = ResType.FLOAT) float imageAspectRatio) {
  MeasureUtils.measureWithAspectRatio(widthSpec, heightSpec, imageAspectRatio, size);
}
 
Example #23
Source File: EditTextSpec.java    From litho with Apache License 2.0 5 votes vote down vote up
@OnBind
static void onBind(
    ComponentContext c,
    EditTextWithEventHandlers editText,
    @Prop(optional = true) EditTextStateUpdatePolicy stateUpdatePolicy,
    @Prop(optional = true, varArg = "textWatcher") List<TextWatcher> textWatchers) {
  editText.setComponentContext(c);
  editText.setTextChangedEventHandler(
      com.facebook.litho.widget.EditText.getTextChangedEventHandler(c));
  editText.setSelectionChangedEventHandler(
      com.facebook.litho.widget.EditText.getSelectionChangedEventHandler(c));
  editText.setKeyUpEventHandler(com.facebook.litho.widget.EditText.getKeyUpEventHandler(c));
  editText.setStateUpdatePolicy(stateUpdatePolicy);
  editText.attachWatchers(textWatchers);
}
 
Example #24
Source File: TestMountSpec.java    From litho with Apache License 2.0 5 votes vote down vote up
@OnEvent(ClickEvent.class)
static void testLayoutEvent(
    ComponentContext c,
    @Prop Object prop3,
    @Prop char prop5,
    @FromEvent View view,
    @Param int param1,
    @State(canUpdateLazily = true) long state1,
    @CachedValue int cached) {}
 
Example #25
Source File: TestTransitionComponent.java    From litho with Apache License 2.0 5 votes vote down vote up
public static Builder create(
    ComponentContext context,
    @AttrRes int defStyleAttr,
    @StyleRes int defStyleRes,
    Component component) {
  return newBuilder(context, defStyleAttr, defStyleRes, new TestTransitionComponent(component));
}
 
Example #26
Source File: StoryHeaderComponentSpec.java    From litho with Apache License 2.0 5 votes vote down vote up
@OnCreateLayout
static Component onCreateLayout(ComponentContext c, @Prop String title, @Prop String subtitle) {
  return Row.create(c)
      .paddingDip(HORIZONTAL, CARD_INSET)
      .paddingDip(TOP, CARD_INSET)
      .child(
          FrescoImage.create(c)
              .controller(
                  Fresco.newDraweeControllerBuilder()
                      .setUri("http://placekitten.com/g/200/200")
                      .build())
              .widthDip(40)
              .heightDip(40)
              .marginDip(END, CARD_INTERNAL_PADDING)
              .marginDip(BOTTOM, CARD_INTERNAL_PADDING))
      .child(
          Column.create(c)
              .flexGrow(1f)
              .child(
                  Text.create(c, 0, R.style.header_title)
                      .text(title)
                      .paddingDip(BOTTOM, CARD_INTERNAL_PADDING))
              .child(
                  Text.create(c, 0, R.style.header_subtitle)
                      .text(subtitle)
                      .paddingDip(BOTTOM, CARD_INTERNAL_PADDING)))
      .child(
          Image.create(c)
              .drawableRes(R.drawable.menu)
              .clickHandler(StoryHeaderComponent.onClickMenuButton(c))
              .widthDip(15)
              .heightDip(15)
              .marginDip(START, CARD_INTERNAL_PADDING)
              .marginDip(BOTTOM, CARD_INTERNAL_PADDING))
      .build();
}
 
Example #27
Source File: TestLayout.java    From litho with Apache License 2.0 5 votes vote down vote up
private void testLayoutEvent(
    HasEventDispatcher _abstract, ComponentContext c, View view, int param1) {
  TestLayout _ref = (TestLayout) _abstract;
  TestLayoutStateContainer stateContainer = getStateContainerWithLazyStateUpdatesApplied(c, _ref);
  TestLayoutSpec.testLayoutEvent(
      c,
      view,
      param1,
      (Object) _ref.prop3,
      (char) _ref.prop5,
      (float) _ref.aspectRatio,
      (boolean) _ref.focusable,
      (long) stateContainer.state1);
}
 
Example #28
Source File: AnimatedBadgeSpec.java    From litho with Apache License 2.0 5 votes vote down vote up
@OnCreateLayout
static Component onCreateLayout(ComponentContext c, @State int state) {
  final boolean expanded1 = state == 1 || state == 2;
  final boolean expanded2 = state == 2 || state == 3;
  return Column.create(c)
      .paddingDip(YogaEdge.ALL, 8)
      .child(Row.create(c).marginDip(YogaEdge.TOP, 8).child(buildComment1(c, expanded1)))
      .child(Row.create(c).marginDip(YogaEdge.TOP, 16).child(buildComment2(c, expanded2)))
      .clickHandler(AnimatedBadge.onClick(c))
      .build();
}
 
Example #29
Source File: ExpandableElementRootComponentSpec.java    From litho with Apache License 2.0 5 votes vote down vote up
@OnCreateLayout
static Component onCreateLayout(
    ComponentContext c, @State List<Message> messages, @State int counter) {
  return Column.create(c)
      .child(
          Row.create(c)
              .backgroundColor(Color.LTGRAY)
              .child(
                  Text.create(c)
                      .paddingDip(YogaEdge.ALL, 10)
                      .text("INSERT")
                      .textSizeSp(20)
                      .flexGrow(1)
                      .alignSelf(YogaAlign.CENTER)
                      .testKey("INSERT")
                      .alignment(TextAlignment.CENTER)
                      .clickHandler(ExpandableElementRootComponent.onClick(c, true)))
              .child(
                  Text.create(c)
                      .paddingDip(YogaEdge.ALL, 10)
                      .text("DELETE")
                      .textSizeSp(20)
                      .flexGrow(1)
                      .alignSelf(YogaAlign.CENTER)
                      .alignment(TextAlignment.CENTER)
                      .clickHandler(ExpandableElementRootComponent.onClick(c, false))))
      .child(
          RecyclerCollectionComponent.create(c)
              .flexGrow(1)
              .disablePTR(true)
              .itemAnimator(new NotAnimatedItemAnimator())
              .section(
                  DataDiffSection.<Message>create(new SectionContext(c))
                      .data(messages)
                      .renderEventHandler(ExpandableElementRootComponent.onRender(c))
                      .build())
              .paddingDip(YogaEdge.TOP, 8))
      .build();
}
 
Example #30
Source File: MountSpecWithShouldUpdateSpec.java    From litho with Apache License 2.0 5 votes vote down vote up
@OnUnmount
static void onUnmount(
    ComponentContext c,
    View v,
    @Prop List<LifecycleStep> operationsOutput,
    @Prop Object objectForShouldUpdate) {
  operationsOutput.add(LifecycleStep.ON_UNMOUNT);
}