cond.py 5.6 KB

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