com.facebook.litho.annotations.State Java Examples

The following examples show how to use com.facebook.litho.annotations.State. 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: HorizontalScrollRootComponentSpec.java    From litho with Apache License 2.0 6 votes vote down vote up
@OnEvent(ClickEvent.class)
static void onClick(
    ComponentContext c,
    @State(canUpdateLazily = true) int prependCounter,
    @State(canUpdateLazily = true) int appendCounter,
    @State ImmutableList<Pair<String, Integer>> items,
    @Param boolean isPrepend) {
  final ArrayList<Pair<String, Integer>> updatedItems = new ArrayList<>(items);
  if (isPrepend) {
    updatedItems.add(0, new Pair<>("Prepend#" + prependCounter, 0xFF7CFC00));
    HorizontalScrollRootComponent.lazyUpdatePrependCounter(c, ++prependCounter);
  } else {
    updatedItems.add(new Pair<>("Append#" + appendCounter, 0xFF6495ED));
    HorizontalScrollRootComponent.lazyUpdateAppendCounter(c, ++appendCounter);
  }
  HorizontalScrollRootComponent.updateItems(
      c, new ImmutableList.Builder<Pair<String, Integer>>().addAll(updatedItems).build());
}
 
Example #2
Source File: SharedElementsComponentSpec.java    From litho with Apache License 2.0 6 votes vote down vote up
@OnEvent(ClickEvent.class)
static void onClickEvent(
    ComponentContext c, @FromEvent View view, @Param int color, @State boolean landLitho) {
  Activity activity = (Activity) c.getAndroidContext();
  Intent intent = new Intent(c.getAndroidContext(), DetailActivity.class);
  intent.putExtra(INTENT_COLOR_KEY, color);
  intent.putExtra(INTENT_LAND_LITHO, landLitho);
  ActivityOptionsCompat options =
      ActivityOptionsCompat.makeSceneTransitionAnimation(
          activity,
          new Pair<View, String>(view, SQUARE_TRANSITION_NAME),
          new Pair<View, String>(
              activity.getWindow().getDecorView().findViewWithTag(TITLE_TRANSITION_NAME),
              TITLE_TRANSITION_NAME));
  activity.startActivity(intent, options.toBundle());
}
 
Example #3
Source File: SizeSpecMountWrapperComponentSpec.java    From litho with Apache License 2.0 6 votes vote down vote up
@OnDetached
static void onDetached(
    ComponentContext c, @State AtomicReference<ComponentTree> componentTreeRef) {
  // We need to release the component tree here to allow for a proper memory deallocation
  final ComponentTree componentTree = componentTreeRef.get();
  if (componentTree != null) {
    componentTreeRef.set(null);
    if (ThreadUtils.isMainThread()) {
      componentTree.release();
    } else {
      sMainThreadHandler.post(
          new Runnable() {
            @Override
            public void run() {
              componentTree.release();
            }
          });
    }
  }
}
 
Example #4
Source File: SizeSpecMountWrapperComponentSpec.java    From litho with Apache License 2.0 6 votes vote down vote up
@OnBoundsDefined
static void onBoundsDefined(
    ComponentContext c,
    ComponentLayout layout,
    @Prop Component component,
    @State AtomicReference<ComponentTree> componentTreeRef) {
  // the updated width and height is passed down.
  int widthSpec = SizeSpec.makeSizeSpec(layout.getWidth(), SizeSpec.EXACTLY);
  int heightSpec = SizeSpec.makeSizeSpec(layout.getHeight(), SizeSpec.EXACTLY);
  final ComponentTree componentTree = getOrCreateComponentTree(c, componentTreeRef);
  // This check is also done in the setRootAndSizeSpec method, but we need to do this here since
  // it will fail if a ErrorBoundariesConfiguration.rootWrapperComponentFactory was set.
  // TODO: T60426216
  if (!componentTree.hasCompatibleLayout(widthSpec, heightSpec)) {
    componentTree.setVersionedRootAndSizeSpec(
        component,
        widthSpec,
        heightSpec,
        null,
        getTreePropWithSize(c, widthSpec, heightSpec),
        c.getLayoutVersion());
  }
}
 
Example #5
Source File: VerySimpleGroupSectionSpec.java    From litho with Apache License 2.0 6 votes vote down vote up
@OnCreateChildren
protected static Children onCreateChildren(
    SectionContext c, @State(canUpdateLazily = true) int extra, @Prop int numberOfDummy) {
  Children.Builder builder = Children.create();

  if (extra > 0) {
    builder.child(
        SingleComponentSection.create(c)
            .component(Image.create(c).drawable(new ColorDrawable()).build()));
  }

  for (int i = 0; i < numberOfDummy + extra; i++) {
    builder.child(
        SingleComponentSection.create(c)
            .component(Text.create(c).text("Lol hi " + i).build())
            .key("key" + i)
            .build());
  }
  return builder.build();
}
 
Example #6
Source File: TextInputSpec.java    From litho with Apache License 2.0 6 votes vote down vote up
@OnTrigger(SetTextEvent.class)
static void setText(
    ComponentContext c,
    @State AtomicReference<EditTextWithEventHandlers> mountedView,
    @State AtomicReference<CharSequence> savedText,
    @FromTrigger CharSequence text) {
  ThreadUtils.assertMainThread();

  EditTextWithEventHandlers view = mountedView.get();
  if (view != null) {
    // If line count changes state update will be triggered by view
    view.setText(text);
  } else {
    savedText.set(text);
    com.facebook.litho.widget.TextInput.remeasureForUpdatedTextSync(c);
  }
}
 
Example #7
Source File: LayoutSpecLifecycleTesterSpec.java    From litho with Apache License 2.0 6 votes vote down vote up
@OnCreateLayout
static Component onCreateLayout(
    ComponentContext c,
    @Prop List<LifecycleStep.StepInfo> steps,
    @Prop(optional = true) @Nullable Caller caller,
    @State String state,
    @CachedValue int expensiveValue) {
  steps.add(new StepInfo(LifecycleStep.ON_CREATE_LAYOUT));
  if (state == null) {
    throw new IllegalStateException("OnCreateLayout called without initialised state.");
  }
  if (caller != null) {
    caller.set(c, steps);
  }
  return Column.create(c).build();
}
 
Example #8
Source File: TestLayoutSpec.java    From litho with Apache License 2.0 6 votes vote down vote up
@OnCreateLayout
static <S extends View> Component onCreateLayout(
    ComponentContext context,
    @Prop @Nullable Object prop3,
    @Prop char[] prop4,
    @Prop EventHandler<ClickEvent> handler,
    @Prop Component child,
    @Prop(optional = true) boolean prop2,
    @Prop(resType = ResType.STRING, optional = true, varArg = "name") List<String> names,
    @State(canUpdateLazily = true) long state1,
    @State S state2,
    @State int state3,
    @TreeProp TestTreeProp treeProp,
    @CachedValue int cached) {
  return null;
}
 
Example #9
Source File: MethodParamModelFactoryTest.java    From litho with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateStateModel() {
  final List<Annotation> annotations = new ArrayList<>();
  annotations.add(mock(State.class));
  MethodParamModel methodParamModel =
      MethodParamModelFactory.create(
          new TypeSpec(TypeName.BOOLEAN),
          "testParam",
          annotations,
          new ArrayList<AnnotationSpec>(),
          ImmutableList.<Class<? extends Annotation>>of(),
          true,
          null);

  assertThat(methodParamModel).isInstanceOf(StateParamModel.class);
}
 
Example #10
Source File: BlocksSameTransitionKeyComponentSpec.java    From litho with Apache License 2.0 6 votes vote down vote up
@OnCreateLayout
static Component onCreateLayout(
    ComponentContext c,
    @State boolean state,
    @State boolean running,
    @State Set<String> runningAnimations) {
  return Column.create(c)
      .child(Row.create(c).child(Text.create(c).text(running ? "RUNNING" : "STOPPED")))
      .child(
          Column.create(c)
              .alignItems(!state ? YogaAlign.FLEX_START : YogaAlign.FLEX_END)
              .child(
                  Text.create(c)
                      .heightDip(50)
                      .widthDip(50)
                      .text(runningAnimations.toString())
                      .backgroundColor(Color.parseColor("#ee1111"))
                      .alpha(!state ? 1.0f : 0.2f)
                      .transitionKey(TRANSITION_KEY)
                      .build()))
      .clickHandler(BlocksSameTransitionKeyComponent.onClick(c))
      .build();
}
 
Example #11
Source File: TransitionEndCallbackTestComponentSpec.java    From litho with Apache License 2.0 6 votes vote down vote up
@OnEvent(TransitionEndEvent.class)
static void onTransitionEnd(
    ComponentContext c,
    @FromEvent String transitionKey,
    @FromEvent AnimatedProperty property,
    @State boolean state,
    @Prop Caller caller) {
  switch (caller.testType) {
    case SAME_KEY:
      if (property == AnimatedProperties.X) {
        caller.transitionEndMessage = ANIM_X;
      } else {
        caller.transitionEndMessage = ANIM_ALPHA;
      }
      break;
    case DISAPPEAR:
      caller.transitionEndMessage = !state ? ANIM_DISAPPEAR : "";
      break;
  }
}
 
Example #12
Source File: AnimationStateExampleComponentSpec.java    From litho with Apache License 2.0 6 votes vote down vote up
@OnCreateLayout
static Component onCreateLayout(
    ComponentContext c, @State boolean shouldAlignStart, @State String actualPosition) {
  return Column.create(c)
      .paddingDip(YogaEdge.ALL, 20)
      .alignItems(shouldAlignStart ? YogaAlign.FLEX_START : YogaAlign.FLEX_END)
      .child(
          Text.create(c)
              .text(actualPosition)
              .textColor(Color.WHITE)
              .textSizeDip(20)
              .alignment(TextAlignment.CENTER)
              .heightDip(SIZE_DP)
              .widthDip(SIZE_DP)
              .backgroundColor(Color.RED))
      .clickHandler(AnimationStateExampleComponent.onClick(c))
      .build();
}
 
Example #13
Source File: SpecModelUtils.java    From litho with Apache License 2.0 5 votes vote down vote up
/** @return the model for state/prop that this Diff is refering to. */
public static MethodParamModel getReferencedParamModelForDiff(
    SpecModel specModel, RenderDataDiffModel diffModel) {
  if (MethodParamModelUtils.isAnnotatedWith(diffModel, Prop.class)) {
    return SpecModelUtils.getPropWithName(specModel, diffModel.getName());
  } else if (MethodParamModelUtils.isAnnotatedWith(diffModel, State.class)) {
    return SpecModelUtils.getStateValueWithName(specModel, diffModel.getName());
  }

  throw new RuntimeException(
      "Diff model wasn't annotated with @State or @Prop, some validation failed");
}
 
Example #14
Source File: CallbackExampleComponentSpec.java    From litho with Apache License 2.0 5 votes vote down vote up
@OnCreateLayout
static Component onCreateLayout(ComponentContext c, @State DynamicValue<Float> scale) {
  return Column.create(c)
      .alignItems(YogaAlign.CENTER)
      .justifyContent(YogaJustify.CENTER)
      .paddingDip(YogaEdge.ALL, 50)
      .clickHandler(CallbackExampleComponent.onClick(c))
      .child(Text.create(c).text("\uD83D\uDE18").textSizeSp(50).scaleX(scale).scaleY(scale))
      .build();
}
 
Example #15
Source File: FullGroupSectionSpec.java    From litho with Apache License 2.0 5 votes vote down vote up
@OnEvent(ClickEvent.class)
static void testEvent(
    SectionContext c,
    @FromEvent(baseClass = View.class) TextView view,
    @Param int someParam,
    @State(canUpdateLazily = true) Object state2,
    @Prop(optional = true) String prop2) {}
 
Example #16
Source File: CachedValueGeneratorTest.java    From litho with Apache License 2.0 5 votes vote down vote up
@OnCreateLayout
public <E extends CharSequence> void testDelegateMethod(
    @Prop boolean arg0,
    @Prop @Nullable Component arg1,
    @Prop List<Component> arg2,
    @Prop List<String> arg3,
    @Prop E genericArg,
    @State int arg4,
    @Param Object arg5,
    @TreeProp long arg6,
    @TreeProp Set<List<Row>> arg7,
    @TreeProp Set<Integer> arg8) {}
 
Example #17
Source File: StoryFooterComponentSpec.java    From litho with Apache License 2.0 5 votes vote down vote up
@OnCreateTransition
static Transition onCreateTransition(ComponentContext c, @State Diff<Boolean> commentText) {
  if (commentText.getPrevious() == null) {
    return null;
  }

  return Transition.parallel(
      Transition.create("comment_editText")
          .animate(AnimatedProperties.ALPHA)
          .appearFrom(0)
          .disappearTo(0)
          .animate(AnimatedProperties.X)
          .appearFrom(DimensionValue.widthPercentageOffset(-50))
          .disappearTo(DimensionValue.widthPercentageOffset(-50)),
      Transition.create("cont_comment")
          .animate(AnimatedProperties.ALPHA)
          .appearFrom(0)
          .disappearTo(0),
      Transition.create("icon_like", "icon_share").animate(AnimatedProperties.X),
      Transition.create("text_like", "text_share")
          .animate(AnimatedProperties.ALPHA)
          .appearFrom(0)
          .disappearTo(0)
          .animate(AnimatedProperties.X)
          .appearFrom(DimensionValue.widthPercentageOffset(50))
          .disappearTo(DimensionValue.widthPercentageOffset(50)));
}
 
Example #18
Source File: LearningStateComponentSpec.java    From litho with Apache License 2.0 5 votes vote down vote up
@OnCreateLayout
static Component onCreateLayout(
    ComponentContext c, @Prop(optional = true) boolean canClick, @State Integer count) {
  return Text.create(c)
      .text("Clicked " + count + " times.")
      .textSizeDip(50)
      .clickHandler(canClick ? LearningStateComponent.onClick(c) : null)
      .backgroundRes(android.R.color.holo_blue_light)
      .alignSelf(STRETCH)
      .paddingDip(BOTTOM, 20)
      .paddingDip(TOP, 40)
      .build();
}
 
Example #19
Source File: DiffValidationTest.java    From litho with Apache License 2.0 5 votes vote down vote up
@Test
public void testDiffModelHasNoTypeParameter() {
  when(mDiffModel.getTypeName())
      .thenReturn(ClassNames.DIFF.annotated(AnnotationSpec.builder(State.class).build()));

  List<SpecModelValidationError> validationErrors = DiffValidation.validate(mSpecModel);
  assertSingleError(validationErrors, DiffValidation.MISSING_TYPE_PARAMETER_ERROR);
}
 
Example #20
Source File: LeftRightBlocksComponentSpec.java    From litho with Apache License 2.0 5 votes vote down vote up
@OnCreateLayout
static Component onCreateLayout(ComponentContext c, @State boolean left) {
  return Column.create(c)
      .alignItems(left ? YogaAlign.FLEX_START : YogaAlign.FLEX_END)
      .child(
          Row.create(c)
              .heightDip(40)
              .widthDip(40)
              .backgroundColor(Color.parseColor("#ee1111"))
              .transitionKey("red")
              .build())
      .child(
          Row.create(c)
              .heightDip(40)
              .widthDip(40)
              .backgroundColor(Color.parseColor("#1111ee"))
              .transitionKey("blue")
              .build())
      .child(
          Row.create(c)
              .heightDip(40)
              .widthDip(40)
              .backgroundColor(Color.parseColor("#11ee11"))
              .transitionKey("green")
              .build())
      .child(
          Row.create(c)
              .heightDip(40)
              .widthDip(40)
              .backgroundColor(Color.BLACK)
              .transitionKey("black")
              .build())
      .clickHandler(LeftRightBlocksComponent.onClick(c))
      .build();
}
 
Example #21
Source File: FullGroupSectionSpec.java    From litho with Apache License 2.0 5 votes vote down vote up
@OnCreateChildren
protected static <T> Children onCreateChildren(
    SectionContext c,
    @Prop Component prop3,
    @Prop(resType = ResType.STRING) String prop4,
    @Prop Section prop5,
    @State T state1) {
  return null;
}
 
Example #22
Source File: CachedValueGeneratorTest.java    From litho with Apache License 2.0 5 votes vote down vote up
@OnEvent(Object.class)
public void testEventMethod(
    @Prop boolean arg0,
    @Prop @Nullable Component arg1,
    @State int arg2,
    @Param Object arg3,
    @TreeProp long arg4) {}
 
Example #23
Source File: ComponentBodyGeneratorTest.java    From litho with Apache License 2.0 5 votes vote down vote up
@OnEvent(Object.class)
public void testEventMethod(
    @Prop boolean arg0,
    @State int arg1,
    @Param Object arg2,
    @TreeProp long arg3,
    @Prop @Nullable Component arg4) {}
 
Example #24
Source File: ExpandableElementMeSpec.java    From litho with Apache License 2.0 5 votes vote down vote up
@OnCreateLayout
static Component onCreateLayout(
    ComponentContext c,
    @Prop String messageText,
    @Prop String timestamp,
    @Prop(optional = true) boolean seen,
    @State Boolean expanded) {
  final boolean isExpanded = expanded == null ? false : expanded;
  return Column.create(c)
      .paddingDip(YogaEdge.TOP, 8)
      .transitionKey(TRANSITION_MSG_PARENT)
      .transitionKeyType(Transition.TransitionKeyType.GLOBAL)
      .clickHandler(ExpandableElementMe.onClick(c))
      .child(ExpandableElementUtil.maybeCreateTopDetailComponent(c, isExpanded, timestamp))
      .child(
          Column.create(c)
              .transitionKey(ExpandableElementUtil.TRANSITION_TEXT_MESSAGE_WITH_BOTTOM)
              .transitionKeyType(Transition.TransitionKeyType.GLOBAL)
              .child(
                  Row.create(c)
                      .justifyContent(YogaJustify.FLEX_END)
                      .paddingDip(YogaEdge.START, 75)
                      .paddingDip(YogaEdge.END, 5)
                      .child(createMessageContent(c, messageText)))
              .child(ExpandableElementUtil.maybeCreateBottomDetailComponent(c, isExpanded, seen)))
      .build();
}
 
Example #25
Source File: StatePropCompletionContributor.java    From litho with Apache License 2.0 5 votes vote down vote up
private static CompletionProvider<CompletionParameters> typeCompletionProvider() {
  return new CompletionProvider<CompletionParameters>() {
    @Override
    protected void addCompletions(
        @NotNull CompletionParameters completionParameters,
        ProcessingContext processingContext,
        @NotNull CompletionResultSet completionResultSet) {
      PsiElement element = completionParameters.getPosition();

      // Method parameter type in the Spec class
      // PsiIdentifier -> PsiJavaCodeReferenceElement -> PsiTypeElement -> PsiMethod -> PsiClass
      PsiElement typeElement = PsiTreeUtil.getParentOfType(element, PsiTypeElement.class);
      if (typeElement == null) {
        return;
      }
      PsiMethod containingMethod = PsiTreeUtil.getParentOfType(element, PsiMethod.class);
      if (containingMethod == null) {
        return;
      }
      PsiClass cls = containingMethod.getContainingClass();
      if (!LithoPluginUtils.isLithoSpec(cls)) {
        return;
      }

      // @Prop or @State annotation
      PsiModifierList parameterModifiers =
          PsiTreeUtil.getPrevSiblingOfType(typeElement, PsiModifierList.class);
      if (parameterModifiers == null) {
        return;
      }
      if (parameterModifiers.findAnnotation(Prop.class.getName()) != null) {
        addCompletionResult(
            completionResultSet, containingMethod, cls.getMethods(), LithoPluginUtils::isProp);
      } else if (parameterModifiers.findAnnotation(State.class.getName()) != null) {
        addCompletionResult(
            completionResultSet, containingMethod, cls.getMethods(), LithoPluginUtils::isState);
      }
    }
  };
}
 
Example #26
Source File: ComponentBodyGeneratorTest.java    From litho with Apache License 2.0 5 votes vote down vote up
@OnCreateLayout
public void testDelegateMethod(
    @Prop boolean arg0,
    @State int arg1,
    @Param Object arg2,
    @TreeProp long arg3,
    @Prop List<String> arg6,
    @TreeProp Set<List<Row>> arg7,
    @TreeProp Set<Integer> arg8) {}
 
Example #27
Source File: FastScrollHandleComponentSpec.java    From litho with Apache License 2.0 5 votes vote down vote up
@OnEvent(TouchEvent.class)
static boolean onTouchEvent(
    ComponentContext c,
    @FromEvent View view,
    @FromEvent MotionEvent motionEvent,
    @State ScrollController scrollController) {
  return scrollController.onTouch(view, motionEvent);
}
 
Example #28
Source File: RowItemSpec.java    From litho with Apache License 2.0 5 votes vote down vote up
@OnCreateLayout
static Component onCreateLayout(ComponentContext c, @State boolean favourited) {
  return Row.create(c)
      .backgroundRes(favourited ? star_on : star_off)
      .widthDip(32)
      .heightDip(32)
      .clickHandler(RowItem.onClick(c))
      .build();
}
 
Example #29
Source File: ErrorBoundarySpec.java    From litho with Apache License 2.0 5 votes vote down vote up
@OnCreateLayout
static Component onCreateLayout(
    ComponentContext c, @Prop Component child, @State @Nullable Exception error) {

  if (error != null) {
    return DebugErrorComponent.create(c).message("Error Boundary").throwable(error).build();
  }

  return child;
}
 
Example #30
Source File: TriggerGeneratorTest.java    From litho with Apache License 2.0 5 votes vote down vote up
@OnTrigger(TestEvent.class)
public Object testTriggerMethod1(
    @Prop boolean arg0,
    @State int arg1,
    @Param Object arg2,
    @Param T arg3,
    @FromTrigger long arg4) {

  return null;
}