cond.py 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  1. """Create a list of components from an iterable."""
  2. from __future__ import annotations
  3. from typing import Any, Dict, Optional, overload
  4. from reflex.components.base.fragment import Fragment
  5. from reflex.components.component import BaseComponent, Component, MemoizationLeaf
  6. from reflex.components.tags import CondTag, Tag
  7. from reflex.constants import Dirs
  8. from reflex.style import LIGHT_COLOR_MODE, resolved_color_mode
  9. from reflex.utils.imports import ImportDict, ImportVar
  10. from reflex.vars import VarData
  11. from reflex.vars.base import LiteralVar, Var
  12. from reflex.vars.number import ternary_operation
  13. _IS_TRUE_IMPORT: ImportDict = {
  14. f"$/{Dirs.STATE_PATH}": [ImportVar(tag="isTrue")],
  15. }
  16. class Cond(MemoizationLeaf):
  17. """Render one of two components based on a condition."""
  18. # The cond to determine which component to render.
  19. cond: Var[Any]
  20. # The component to render if the cond is true.
  21. comp1: BaseComponent | None = None
  22. # The component to render if the cond is false.
  23. comp2: BaseComponent | None = None
  24. @classmethod
  25. def create(
  26. cls,
  27. cond: Var,
  28. comp1: BaseComponent,
  29. comp2: Optional[BaseComponent] = None,
  30. ) -> Component:
  31. """Create a conditional component.
  32. Args:
  33. cond: The cond to determine which component to render.
  34. comp1: The component to render if the cond is true.
  35. comp2: The component to render if the cond is false.
  36. Returns:
  37. The conditional component.
  38. """
  39. # Wrap everything in fragments.
  40. if type(comp1).__name__ != "Fragment":
  41. comp1 = Fragment.create(comp1)
  42. if comp2 is None or type(comp2).__name__ != "Fragment":
  43. comp2 = Fragment.create(comp2) if comp2 else Fragment.create()
  44. return Fragment.create(
  45. cls(
  46. cond=cond,
  47. comp1=comp1,
  48. comp2=comp2,
  49. children=[comp1, comp2],
  50. )
  51. )
  52. def _get_props_imports(self):
  53. """Get the imports needed for component's props.
  54. Returns:
  55. The imports for the component's props of the component.
  56. """
  57. return []
  58. def _render(self) -> Tag:
  59. return CondTag(
  60. cond=self.cond,
  61. true_value=self.comp1.render(), # pyright: ignore [reportOptionalMemberAccess]
  62. false_value=self.comp2.render(), # pyright: ignore [reportOptionalMemberAccess]
  63. )
  64. def render(self) -> Dict:
  65. """Render the component.
  66. Returns:
  67. The dictionary for template of component.
  68. """
  69. tag = self._render()
  70. return dict(
  71. tag.add_props(
  72. **self.event_triggers,
  73. key=self.key,
  74. sx=self.style,
  75. id=self.id,
  76. class_name=self.class_name,
  77. ).set(
  78. props=tag.format_props(),
  79. ),
  80. cond_state=f"isTrue({self.cond!s})",
  81. )
  82. def add_imports(self) -> ImportDict:
  83. """Add imports for the Cond component.
  84. Returns:
  85. The import dict for the component.
  86. """
  87. var_data = VarData.merge(self.cond._get_all_var_data())
  88. imports = var_data.old_school_imports() if var_data else {}
  89. return {**imports, **_IS_TRUE_IMPORT}
  90. @overload
  91. def cond(condition: Any, c1: Component, c2: Any) -> Component: ... # pyright: ignore [reportOverlappingOverload]
  92. @overload
  93. def cond(condition: Any, c1: Component) -> Component: ...
  94. @overload
  95. def cond(condition: Any, c1: Any, c2: Any) -> Var: ...
  96. def cond(condition: Any, c1: Any, c2: Any = None) -> Component | Var:
  97. """Create a conditional component or Prop.
  98. Args:
  99. condition: The cond to determine which component to render.
  100. c1: The component or prop to render if the cond_var is true.
  101. c2: The component or prop to render if the cond_var is false.
  102. Returns:
  103. The conditional component.
  104. Raises:
  105. ValueError: If the arguments are invalid.
  106. """
  107. # Convert the condition to a Var.
  108. cond_var = LiteralVar.create(condition)
  109. if cond_var is None:
  110. raise ValueError("The condition must be set.")
  111. # If the first component is a component, create a Cond component.
  112. if isinstance(c1, BaseComponent):
  113. if c2 is not None and not isinstance(c2, BaseComponent):
  114. raise ValueError("Both arguments must be components.")
  115. return Cond.create(cond_var, c1, c2)
  116. # Otherwise, create a conditional Var.
  117. # Check that the second argument is valid.
  118. if isinstance(c2, BaseComponent):
  119. raise ValueError("Both arguments must be props.")
  120. if c2 is None:
  121. raise ValueError("For conditional vars, the second argument must be set.")
  122. def create_var(cond_part: Any) -> Var[Any]:
  123. return LiteralVar.create(cond_part)
  124. # convert the truth and false cond parts into vars so the _var_data can be obtained.
  125. c1 = create_var(c1)
  126. c2 = create_var(c2)
  127. # Create the conditional var.
  128. return ternary_operation(
  129. cond_var.bool()._replace(
  130. merge_var_data=VarData(imports=_IS_TRUE_IMPORT),
  131. ),
  132. c1,
  133. c2,
  134. )
  135. @overload
  136. def color_mode_cond(light: Component, dark: Component | None = None) -> Component: ... # pyright: ignore [reportOverlappingOverload]
  137. @overload
  138. def color_mode_cond(light: Any, dark: Any = None) -> Var: ...
  139. def color_mode_cond(light: Any, dark: Any = None) -> Var | Component:
  140. """Create a component or Prop based on color_mode.
  141. Args:
  142. light: The component or prop to render if color_mode is default
  143. dark: The component or prop to render if color_mode is non-default
  144. Returns:
  145. The conditional component or prop.
  146. """
  147. return cond(
  148. resolved_color_mode == LiteralVar.create(LIGHT_COLOR_MODE),
  149. light,
  150. dark,
  151. )