foreach.py 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. """Create a list of components from an iterable."""
  2. from __future__ import annotations
  3. from typing import Any, Callable, List
  4. from pynecone.components.component import Component
  5. from pynecone.components.layout.fragment import Fragment
  6. from pynecone.components.tags import IterTag
  7. from pynecone.vars import BaseVar, Var, get_unique_variable_name
  8. class Foreach(Component):
  9. """A component that takes in an iterable and a render function and renders a list of components."""
  10. # The iterable to create components from.
  11. iterable: Var[List]
  12. # A function from the render args to the component.
  13. render_fn: Callable = Fragment.create
  14. @classmethod
  15. def create(cls, iterable: Var[List], render_fn: Callable, **props) -> Foreach:
  16. """Create a foreach component.
  17. Args:
  18. iterable: The iterable to create components from.
  19. render_fn: A function from the render args to the component.
  20. **props: The attributes to pass to each child component.
  21. Returns:
  22. The foreach component.
  23. Raises:
  24. TypeError: If the iterable is of type Any.
  25. """
  26. try:
  27. type_ = iterable.type_.__args__[0]
  28. except Exception:
  29. type_ = Any
  30. iterable = Var.create(iterable) # type: ignore
  31. if iterable.type_ == Any:
  32. raise TypeError(
  33. f"Could not foreach over var of type Any. (If you are trying to foreach over a state var, add a type annotation to the var.)"
  34. )
  35. arg = BaseVar(name="_", type_=type_, is_local=True)
  36. return cls(
  37. iterable=iterable,
  38. render_fn=render_fn,
  39. children=[IterTag.render_component(render_fn, arg=arg)],
  40. **props,
  41. )
  42. def _render(self) -> IterTag:
  43. return IterTag(iterable=self.iterable, render_fn=self.render_fn)
  44. def render(self):
  45. """Render the component.
  46. Returns:
  47. The dictionary for template of component.
  48. """
  49. tag = self._render()
  50. try:
  51. type_ = self.iterable.type_.__args__[0]
  52. except Exception:
  53. type_ = Any
  54. arg = BaseVar(
  55. name=get_unique_variable_name(),
  56. type_=type_,
  57. )
  58. index_arg = tag.get_index_var_arg()
  59. component = tag.render_component(self.render_fn, arg)
  60. return dict(
  61. tag.add_props(
  62. **self.event_triggers,
  63. key=self.key,
  64. sx=self.style,
  65. id=self.id,
  66. class_name=self.class_name,
  67. ).set(
  68. children=[component.render()],
  69. props=tag.format_props(),
  70. ),
  71. iterable_state=tag.iterable.full_name,
  72. arg_name=arg.name,
  73. arg_index=index_arg,
  74. )