foreach.py 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. """Create a list of components from an iterable."""
  2. from __future__ import annotations
  3. import inspect
  4. from hashlib import md5
  5. from typing import Any, Callable, Iterable
  6. from reflex.components.component import Component
  7. from reflex.components.layout.fragment import Fragment
  8. from reflex.components.tags import IterTag
  9. from reflex.vars import Var
  10. class Foreach(Component):
  11. """A component that takes in an iterable and a render function and renders a list of components."""
  12. # The iterable to create components from.
  13. iterable: Var[Iterable]
  14. # A function from the render args to the component.
  15. render_fn: Callable = Fragment.create
  16. @classmethod
  17. def create(cls, iterable: Var[Iterable], render_fn: Callable, **props) -> Foreach:
  18. """Create a foreach component.
  19. Args:
  20. iterable: The iterable to create components from.
  21. render_fn: A function from the render args to the component.
  22. **props: The attributes to pass to each child component.
  23. Returns:
  24. The foreach component.
  25. Raises:
  26. TypeError: If the iterable is of type Any.
  27. """
  28. iterable = Var.create(iterable) # type: ignore
  29. if iterable._var_type == Any:
  30. raise TypeError(
  31. 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.)"
  32. )
  33. component = cls(
  34. iterable=iterable,
  35. render_fn=render_fn,
  36. **props,
  37. )
  38. # Keep a ref to a rendered component to determine correct imports.
  39. component.children = [
  40. component._render(props=dict(index_var_name="i")).render_component()
  41. ]
  42. return component
  43. def _render(self, props: dict[str, Any] | None = None) -> IterTag:
  44. props = {} if props is None else props.copy()
  45. # Determine the arg var name based on the params accepted by render_fn.
  46. render_sig = inspect.signature(self.render_fn)
  47. params = list(render_sig.parameters.values())
  48. if len(params) >= 1:
  49. props.setdefault("arg_var_name", params[0].name)
  50. if len(params) >= 2:
  51. # Determine the index var name based on the params accepted by render_fn.
  52. props.setdefault("index_var_name", params[1].name)
  53. elif "index_var_name" not in props:
  54. # Otherwise, use a deterministic index, based on the rendered code.
  55. code_hash = md5(str(self.children[0].render()).encode("utf-8")).hexdigest()
  56. props.setdefault("index_var_name", f"index_{code_hash}")
  57. return IterTag(
  58. iterable=self.iterable,
  59. render_fn=self.render_fn,
  60. **props,
  61. )
  62. def render(self):
  63. """Render the component.
  64. Returns:
  65. The dictionary for template of component.
  66. """
  67. tag = self._render()
  68. component = tag.render_component()
  69. return dict(
  70. tag.add_props(
  71. **self.event_triggers,
  72. key=self.key,
  73. sx=self.style,
  74. id=self.id,
  75. class_name=self.class_name,
  76. ).set(
  77. children=[component.render()],
  78. props=tag.format_props(),
  79. ),
  80. iterable_state=tag.iterable._var_full_name,
  81. arg_name=tag.arg_var_name,
  82. arg_index=tag.get_index_var_arg(),
  83. iterable_type=tag.iterable._var_type.mro()[0].__name__,
  84. )