cond.py 2.5 KB

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