foreach.py 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136
  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.state import ComponentState
  10. from reflex.vars.base import LiteralVar, 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. ) -> Foreach:
  28. """Create a foreach component.
  29. Args:
  30. iterable: The iterable to create components from.
  31. render_fn: A function from the render args to the component.
  32. Returns:
  33. The foreach component.
  34. Raises:
  35. ForeachVarError: If the iterable is of type Any.
  36. TypeError: If the render function is a ComponentState.
  37. """
  38. iterable = LiteralVar.create(iterable)
  39. if iterable._var_type == Any:
  40. raise ForeachVarError(
  41. f"Could not foreach over var `{iterable!s}` of type Any. "
  42. "(If you are trying to foreach over a state var, add a type annotation to the var). "
  43. "See https://reflex.dev/docs/library/dynamic-rendering/foreach/"
  44. )
  45. if (
  46. hasattr(render_fn, "__qualname__")
  47. and render_fn.__qualname__ == ComponentState.create.__qualname__
  48. ):
  49. raise TypeError(
  50. "Using a ComponentState as `render_fn` inside `rx.foreach` is not supported yet."
  51. )
  52. component = cls(
  53. iterable=iterable,
  54. render_fn=render_fn,
  55. )
  56. # Keep a ref to a rendered component to determine correct imports/hooks/styles.
  57. component.children = [component._render().render_component()]
  58. return component
  59. def _render(self) -> IterTag:
  60. props = {}
  61. render_sig = inspect.signature(self.render_fn)
  62. params = list(render_sig.parameters.values())
  63. # Validate the render function signature.
  64. if len(params) == 0 or len(params) > 2:
  65. raise ForeachRenderError(
  66. "Expected 1 or 2 parameters in foreach render function, got "
  67. f"{[p.name for p in params]}. See "
  68. "https://reflex.dev/docs/library/dynamic-rendering/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=str(tag.iterable),
  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. )
  107. foreach = Foreach.create