cond.py 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  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 # type: ignore
  22. # The component to render if the cond is false.
  23. comp2: BaseComponent = None # type: ignore
  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 comp1.__class__.__name__ != "Fragment":
  41. comp1 = Fragment.create(comp1)
  42. if comp2 is None or comp2.__class__.__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(),
  62. false_value=self.comp2.render(),
  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({str(self.cond)})",
  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: ...
  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 the first component is a component, create a Fragment if the second component is not set.
  110. if isinstance(c1, BaseComponent):
  111. c2 = c2 if c2 is not None else Fragment.create()
  112. # Check that the second argument is valid.
  113. if c2 is None:
  114. raise ValueError("For conditional vars, the second argument must be set.")
  115. # Create the conditional var.
  116. return ternary_operation(
  117. cond_var.bool(),
  118. c1,
  119. c2,
  120. )
  121. @overload
  122. def color_mode_cond(light: Component, dark: Component | None = None) -> Component: ... # type: ignore
  123. @overload
  124. def color_mode_cond(light: Any, dark: Any = None) -> Var: ...
  125. def color_mode_cond(light: Any, dark: Any = None) -> Var | Component:
  126. """Create a component or Prop based on color_mode.
  127. Args:
  128. light: The component or prop to render if color_mode is default
  129. dark: The component or prop to render if color_mode is non-default
  130. Returns:
  131. The conditional component or prop.
  132. """
  133. return cond(
  134. resolved_color_mode == LiteralVar.create(LIGHT_COLOR_MODE),
  135. light,
  136. dark,
  137. )