cond.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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
  6. from reflex.style import LIGHT_COLOR_MODE, resolved_color_mode
  7. from reflex.utils import types
  8. from reflex.utils.types import safe_issubclass
  9. from reflex.vars.base import LiteralVar, Var
  10. from reflex.vars.number import ternary_operation
  11. @overload
  12. def cond(condition: Any, c1: Component, c2: Any = None) -> Component: ...
  13. @overload
  14. def cond(condition: Any, c1: Any, c2: Any) -> Var: ...
  15. def cond(condition: Any, c1: Any, c2: Any = None) -> Component | Var:
  16. """Create a conditional component or Prop.
  17. Args:
  18. condition: The cond to determine which component to render.
  19. c1: The component or prop to render if the cond_var is true.
  20. c2: The component or prop to render if the cond_var is false.
  21. Returns:
  22. The conditional component.
  23. Raises:
  24. ValueError: If the arguments are invalid.
  25. """
  26. # Convert the condition to a Var.
  27. cond_var = LiteralVar.create(condition)
  28. # If the first component is a component, create a Fragment if the second component is not set.
  29. if isinstance(c1, BaseComponent) or (
  30. isinstance(c1, Var)
  31. and (
  32. safe_issubclass(c1._var_type, BaseComponent)
  33. or types.safe_typehint_issubclass(c1._var_type, list[BaseComponent])
  34. )
  35. ):
  36. c2 = c2 if c2 is not None else Fragment.create()
  37. # Check that the second argument is valid.
  38. if c2 is None:
  39. raise ValueError("For conditional vars, the second argument must be set.")
  40. # Create the conditional var.
  41. return ternary_operation(
  42. cond_var.bool(),
  43. c1,
  44. c2,
  45. )
  46. @overload
  47. def color_mode_cond(light: Component, dark: Component | None = None) -> Component: ... # type: ignore
  48. @overload
  49. def color_mode_cond(light: Any, dark: Any = None) -> Var: ...
  50. def color_mode_cond(light: Any, dark: Any = None) -> Var | Component:
  51. """Create a component or Prop based on color_mode.
  52. Args:
  53. light: The component or prop to render if color_mode is default
  54. dark: The component or prop to render if color_mode is non-default
  55. Returns:
  56. The conditional component or prop.
  57. """
  58. return cond(
  59. resolved_color_mode == LiteralVar.create(LIGHT_COLOR_MODE),
  60. light,
  61. dark,
  62. )
  63. class Cond:
  64. """Create a conditional component or Prop."""
  65. create = staticmethod(cond)