foreach.py 3.6 KB

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