foreach.py 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130
  1. """Create a list of components from an iterable."""
  2. from __future__ import annotations
  3. import inspect
  4. from typing import Any, Callable, Iterable
  5. from reflex.components.base.fragment import Fragment
  6. from reflex.components.component import Component
  7. from reflex.components.tags import IterTag
  8. from reflex.constants import MemoizationMode
  9. from reflex.utils import console
  10. from reflex.vars import Var
  11. class ForeachVarError(TypeError):
  12. """Raised when the iterable type is Any."""
  13. class ForeachRenderError(TypeError):
  14. """Raised when there is an error with the foreach render function."""
  15. class Foreach(Component):
  16. """A component that takes in an iterable and a render function and renders a list of components."""
  17. _memoization_mode = MemoizationMode(recursive=False)
  18. # The iterable to create components from.
  19. iterable: Var[Iterable]
  20. # A function from the render args to the component.
  21. render_fn: Callable = Fragment.create
  22. @classmethod
  23. def create(
  24. cls,
  25. iterable: Var[Iterable] | Iterable,
  26. render_fn: Callable,
  27. **props,
  28. ) -> Foreach:
  29. """Create a foreach component.
  30. Args:
  31. iterable: The iterable to create components from.
  32. render_fn: A function from the render args to the component.
  33. **props: The attributes to pass to each child component (deprecated).
  34. Returns:
  35. The foreach component.
  36. Raises:
  37. ForeachVarError: If the iterable is of type Any.
  38. """
  39. if props:
  40. console.deprecate(
  41. feature_name="Passing props to rx.foreach",
  42. reason="it does not have the intended effect and may be confusing",
  43. deprecation_version="0.5.0",
  44. removal_version="0.6.0",
  45. )
  46. iterable = Var.create_safe(iterable)
  47. if iterable._var_type == Any:
  48. raise ForeachVarError(
  49. f"Could not foreach over var `{iterable._var_full_name}` of type Any. "
  50. "(If you are trying to foreach over a state var, add a type annotation to the var). "
  51. "See https://reflex.dev/docs/library/layout/foreach/"
  52. )
  53. component = cls(
  54. iterable=iterable,
  55. render_fn=render_fn,
  56. )
  57. # Keep a ref to a rendered component to determine correct imports/hooks/styles.
  58. component.children = [component._render().render_component()]
  59. return component
  60. def _render(self) -> IterTag:
  61. props = {}
  62. render_sig = inspect.signature(self.render_fn)
  63. params = list(render_sig.parameters.values())
  64. # Validate the render function signature.
  65. if len(params) == 0 or len(params) > 2:
  66. raise ForeachRenderError(
  67. "Expected 1 or 2 parameters in foreach render function, got "
  68. f"{[p.name for p in params]}. See https://reflex.dev/docs/library/layout/foreach/"
  69. )
  70. if len(params) >= 1:
  71. # Determine the arg var name based on the params accepted by render_fn.
  72. props["arg_var_name"] = params[0].name
  73. if len(params) == 2:
  74. # Determine the index var name based on the params accepted by render_fn.
  75. props["index_var_name"] = params[1].name
  76. else:
  77. # Otherwise, use a deterministic index, based on the render function bytecode.
  78. code_hash = (
  79. hash(self.render_fn.__code__)
  80. .to_bytes(
  81. length=8,
  82. byteorder="big",
  83. signed=True,
  84. )
  85. .hex()
  86. )
  87. props["index_var_name"] = f"index_{code_hash}"
  88. return IterTag(
  89. iterable=self.iterable,
  90. render_fn=self.render_fn,
  91. children=self.children,
  92. **props,
  93. )
  94. def render(self):
  95. """Render the component.
  96. Returns:
  97. The dictionary for template of component.
  98. """
  99. tag = self._render()
  100. return dict(
  101. tag,
  102. iterable_state=tag.iterable._var_full_name,
  103. arg_name=tag.arg_var_name,
  104. arg_index=tag.get_index_var_arg(),
  105. iterable_type=tag.iterable._var_type.mro()[0].__name__,
  106. )