cond.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. """Create a list of components from an iterable."""
  2. from __future__ import annotations
  3. from typing import Optional
  4. import pydantic
  5. from pynecone.components.component import Component
  6. from pynecone.components.layout.fragment import Fragment
  7. from pynecone.components.tags import CondTag, Tag
  8. from pynecone.var import Var
  9. class Cond(Component):
  10. """Render one of two components based on a condition."""
  11. # The cond to determine which component to render.
  12. cond: Var[bool]
  13. # The component to render if the cond is true.
  14. comp1: Component
  15. # The component to render if the cond is false.
  16. comp2: Component
  17. # Whether the cond is within another cond.
  18. is_nested: bool = False
  19. @pydantic.validator("cond")
  20. def validate_cond(cls, cond: Var) -> Var:
  21. """Validate that the cond is a boolean.
  22. Args:
  23. cond: The cond to validate.
  24. Returns:
  25. The validated cond.
  26. """
  27. assert issubclass(cond.type_, bool), "The var must be a boolean."
  28. return cond
  29. @classmethod
  30. def create(
  31. cls, cond: Var, comp1: Component, comp2: Optional[Component] = None
  32. ) -> Cond:
  33. """Create a conditional component.
  34. Args:
  35. cond: The cond to determine which component to render.
  36. comp1: The component to render if the cond is true.
  37. comp2: The component to render if the cond is false.
  38. Returns:
  39. The conditional component.
  40. """
  41. if comp2 is None:
  42. comp2 = Fragment.create()
  43. if isinstance(comp1, Cond):
  44. comp1.is_nested = True
  45. if isinstance(comp2, Cond):
  46. comp2.is_nested = True
  47. return cls(
  48. cond=cond,
  49. comp1=comp1,
  50. comp2=comp2,
  51. children=[comp1, comp2],
  52. ) # type: ignore
  53. def _render(self) -> Tag:
  54. return CondTag(
  55. cond=self.cond,
  56. true_value=self.comp1.render(),
  57. false_value=self.comp2.render(),
  58. is_nested=self.is_nested,
  59. )